forked from a-synchronous/rubico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tap.js
102 lines (98 loc) · 2.26 KB
/
tap.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const isPromise = require('./_internal/isPromise')
const always = require('./_internal/always')
const tapSync = require('./_internal/tapSync')
const thunkifyArgs = require('./_internal/thunkifyArgs')
const thunkConditional = require('./_internal/thunkConditional')
const curry3 = require('./_internal/curry3')
const __ = require('./_internal/placeholder')
/**
* @name tap
*
* @synopsis
* ```coffeescript [specscript]
* var args ...any,
* tapper ...args=>Promise|any
*
* tap(tapper)(...args) -> Promise|args[0]
* ```
*
* @description
* Call a function with a value, returning the value. Promises created by the tapper are resolved before returning the value.
*
* ```javascript [playground]
* pipe([
* tap(console.log),
* value => value + 'bar',
* tap(console.log),
* ])('foo') // 'foo'
* // 'foobar'
* ```
*/
const tap = func => function tapping(...args) {
const result = args[0],
call = func(...args)
return isPromise(call) ? call.then(always(result)) : result
}
/**
* @name tap.sync
*
* @synopsis
* ```coffeescript [specscript]
* var args ...any,
* tapper ...args=>any
*
* tap.sync(tapper)(...args) -> args[0]
* ```
*
* @description
* Synchronous `tap`
*
* ```javascript [playground]
* pipe([
* tap.sync(number => console.log('square', number ** 2)),
* tap.sync(number => console.log('cube', number ** 3)),
* ])(3) // 9
* // 27
* ```
*/
tap.sync = tapSync
/**
* @name tap.if
*
* @synopsis
* ```coffeescript [specscript]
* var args ...any,
* predicate ...args=>Promise|boolean,
* tapper ...args=>Promise|any
*
* tap.if(predicate, tapper)(...args) -> Promise|args[0]
* ```
*
* @description
* Conditional `tap` by predicate
*
* ```javascript [playground]
* const isOdd = number => number % 2 == 1
*
* const logIfOdd = tap.if(
* isOdd,
* number => console.log(number, 'is an odd number'))
*
* logIfOdd(2)
* logIfOdd(3) // 3 is an odd number
* ```
*
* @related tap
*/
tap.if = (predicate, func) => function tappingIf(...args) {
const predication = predicate(...args)
if (isPromise(predication)) {
return predication.then(curry3(
thunkConditional, __, thunkifyArgs(tap(func), args), always(args[0])))
}
if (predication) {
func(...args)
}
return args[0]
}
module.exports = tap