-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy patheither.ts
43 lines (37 loc) · 1.39 KB
/
either.ts
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
// Copyright (c) 2020 Jozty. All rights reserved. MIT license.
import curryN from './utils/curry_n.ts';
import type { Func, PH } from './utils/types.ts';
import { isFunction } from './utils/is.ts';
import { lift } from './lift.ts';
import { or } from './or.ts';
// @types
type Either_2<A extends unknown[]> = (g: Func<A>) => Func<A, boolean>;
type Either_1<A extends unknown[]> = (f: Func<A>) => Func<A, boolean>;
type Either =
& (<A extends unknown[]>(f: Func<A>) => Either_2<A>)
& (<A extends unknown[]>(f: PH, g: Func<A>) => Either_1<A>)
& (<A extends unknown[]>(f: Func<A>, g: Func<A>) => Func<A, boolean>);
function _either<T extends Func>(f: T, g: T): T {
if (isFunction(f)) {
const __either = function (this: unknown, ...args: unknown[]) {
return f.apply(this, args) || g.apply(this, args);
};
return __either as T;
} else {
// @ts-ignore: will remove this in future
return lift(or)(f, g);
}
}
/**
* A function wrapping calls to the two functions in an `||` operation,
* returning the result of the first function if it is true and the result
* of the second function otherwise. Second function will not be invoked if the first returns a
* true value.
*
* const gt10 = x => x > 10
* const even = x => (x & 1) === 0
* const f = Fae.either(gt10, even)
* f(101) //=> true
* f(8) //=> true
*/
export const either = curryN(2, _either) as Either;