All files / object/src defaultIf.ts

100% Statements 8/8
100% Branches 2/2
100% Functions 4/4
100% Lines 8/8

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 345x                                             7x 5x 7x 25x 25x 16x   9x      
import { ValueOrProvider, valueOrProviderResult } from "./valueOrProvider";
 
/**
 * If the provided value matches the Predicate, the default value will be returned
 *
 * @example
 * Default to `1` if `value` is less than `0`
 * ```ts
 * const defaultTo1IfNegative = defaultIf(value => value < 0)(1);
 * const n = defaultTo1IfNegative(-1);
 * console.log(n); // 1
 * ```
 *
 * @example
 * Call initializer function if `value` is less than `0`
 * ```ts
 * const callInitFnIfNegative = defaultIf(value => value < 0)(() => 2);
 * const n = callInitFnIfNegative(-1);
 * console.log(n); // 2
 * ```
 *
 * @returns the defaultValue if the Predicate matches, else the provided value
 */
export const defaultIf =
  <T, S extends T>(predicate: (value: T) => value is S) =>
  <D>(defaultValue: ValueOrProvider<D>) =>
  <V extends T>(value: V): Exclude<V, S> | D => {
    if (predicate(value)) {
      return valueOrProviderResult(defaultValue);
    } else {
      return value as Exclude<V, S>;
    }
  };