All files / src derive.ts

100% Statements 3/3
100% Branches 2/2
100% Functions 2/2
100% Lines 3/3

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                                                                          18x     11x 23x  
import { compute } from "./compute";
import { type ReadableLike, type Config, type OwnedReadable } from "./interface";
 
export interface Derive {
  /**
   * Derive a new {@link Readable} with same value from the given {@link ReadableLike}.
   * @param dep - The {@link ReadableLike} to derive from.
   * @returns A {@link Readable} with same value as the given {@link ReadableLike}.
   */
  <TDepValue, TValue>(dep: ReadableLike<TDepValue>): OwnedReadable<TValue>;
  /**
   * Derive a new {@link Readable} with transformed value from the given {@link ReadableLike}.
   * @param dep - The {@link ReadableLike} to derive from.
   * @param transform A pure function that takes an input value and returns a new value.
   * @param config custom config for the combined {@link Readable}.
   * @returns A {@link Readable} with transformed value from the given {@link ReadableLike}.
   */
  <TDepValue, TValue>(
    dep: ReadableLike<TDepValue>,
    transform: (depValue: TDepValue) => TValue,
    config?: Config<TValue>,
  ): OwnedReadable<TValue>;
}
 
/**
 * Derive a new {@link Readable} with transformed value from the given {@link ReadableLike}.
 *
 * Unlike {@link compute}, the signature of the `transform` function is pure,
 * which makes it easier to use functions that are not aware of the reactive system.
 *
 * @function
 * @category Derivations
 * @param dep - The {@link ReadableLike} to derive from.
 * @param transform - Optional pure function that takes an input value and returns a new value.
 * @param config - Optional custom {@link Config}.
 * @returns A {@link OwnedReadable} with transformed value from the given {@link ReadableLike}.
 */
export const derive: Derive = <TDepValue, TValue>(
  dep: ReadableLike<TDepValue>,
  transform?: (depValue: TDepValue) => TValue,
  config?: Config<TValue>,
) => compute(get => (transform ? transform(get(dep)) : (get(dep) as unknown as TValue)), config);