UNPKG

2.02 kBTypeScriptView Raw
1declare type Choice = {
2 when: any;
3 then?: any;
4 ref?: number;
5 use?: any;
6 eager?: Function;
7};
8declare type PlainObject = {
9 [x: string]: any;
10};
11declare type Choices = Choice[] | PlainObject;
12declare type LazyChoices = () => Choices;
13declare type EqualityFn = (input: any, when: any) => boolean;
14/**
15 * The heart of this library, a curried function which stores the specified choices (and extra options) in the first call,
16 * and returns a function that will take the user's input, find the corresponding choice, and return its `then` value.
17 *
18 * It will attempt to resolve it by finding the entry in the `choice` array whose `when` corresponds to the given
19 * `input`. If a `ref` exists in that entry, it will instead find its referenced entry. IF `use` exists in that entry,
20 * it will instead try to find an entry that corresponds to the given `use` instead of `when`.
21 *
22 * The matching between the `input` and the `when` is performed by running the `equalityFn` with the `input` against the value of `when`,
23 * or against each element in `when` if it is an array.
24 *
25 * After all recursive calls have returned and a choice has been found, the `then` of the choice is returned.
26 * If the `then` is a function, it is called and its result is returned instead, to leverage lazy evaluation.
27 *
28 * As an escape hatch for the above lazy evaluation mechanism, a function can be specified under the `eager` key,
29 * and it will be returned as is, without it being executed to extract its result.
30 *
31 * @param choices A `choice` array or a plain object.
32 * @param defaultValue A default value to be returned if the `input` does not yield a choice.
33 * @param equalityFn Used to override the default equality function `eq` from `lodash`.
34 */
35declare const chooser: (choices: PlainObject | Choice[] | LazyChoices, defaultValue?: any, equalityFn?: EqualityFn | undefined) => (input: any, equalityFnOverride?: EqualityFn | undefined) => any;
36export default chooser;