-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy patharrayConditional.js
67 lines (59 loc) · 1.71 KB
/
arrayConditional.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const isPromise = require('./isPromise')
const thunkConditional = require('./thunkConditional')
const thunkifyArgs = require('./thunkifyArgs')
const thunkify3 = require('./thunkify3')
const __ = require('./placeholder')
const curry3 = require('./curry3')
const always = require('./always')
/**
* @name arrayConditional
*
* @synopsis
* ```coffeescript [specscript]
* arrayConditional(
* array Array<function|value>,
* args Array,
* funcsIndex number,
* ) -> Promise|any
* ```
*
* @description
* Conditional operator `a ? b : c ? d : e ? ...` for functions.
*
* @TODO isPromise conditional await
* @TODO benchmark vs regular promise handling
*/
const arrayConditional = function (array, args, funcsIndex) {
const lastIndex = array.length - 1
while ((funcsIndex += 2) < lastIndex) {
const predicate = array[funcsIndex],
resolverOrValue = array[funcsIndex + 1]
const predication = typeof predicate == 'function'
? predicate(...args)
: predicate
if (isPromise(predication)) {
return predication.then(curry3(
thunkConditional,
__,
typeof resolverOrValue == 'function'
? thunkifyArgs(resolverOrValue, args)
: always(resolverOrValue),
thunkify3(arrayConditional, array, args, funcsIndex),
))
}
if (predication) {
return typeof resolverOrValue == 'function'
? resolverOrValue(...args)
: resolverOrValue
}
}
// even number of array
if (funcsIndex == array.length) {
return undefined
}
const defaultResolverOrValue = array[lastIndex]
return typeof defaultResolverOrValue == 'function'
? defaultResolverOrValue(...args)
: defaultResolverOrValue
}
module.exports = arrayConditional