forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cond.js
49 lines (45 loc) · 1.2 KB
/
cond.js
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
44
45
46
47
48
49
import map from './map.js'
/**
* Creates a function that iterates over `pairs` and invokes the corresponding
* function of the first predicate to return truthy. The predicate-function
* pairs are invoked with the `this` binding and arguments of the created
* function.
*
* @since 4.0.0
* @category Util
* @param {Array} pairs The predicate-function pairs.
* @returns {Function} Returns the new composite function.
* @example
*
* const func = cond([
* [matches({ 'a': 1 }), () => 'matches A'],
* [conforms({ 'b': isNumber }), () => 'matches B'],
* [() => true, () => 'no match']
* ])
*
* func({ 'a': 1, 'b': 2 })
* // => 'matches A'
*
* func({ 'a': 0, 'b': 1 })
* // => 'matches B'
*
* func({ 'a': '1', 'b': '2' })
* // => 'no match'
*/
function cond(pairs) {
const length = pairs == null ? 0 : pairs.length
pairs = !length ? [] : map(pairs, (pair) => {
if (typeof pair[1] !== 'function') {
throw new TypeError('Expected a function')
}
return [pair[0], pair[1]]
})
return (...args) => {
for (const pair of pairs) {
if (pair[0].apply(this, args)) {
return pair[1].apply(this, args)
}
}
}
}
export default cond