-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
once.js
36 lines (34 loc) · 978 Bytes
/
once.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
import _arity from './internal/_arity';
import _curry1 from './internal/_curry1';
/**
* Accepts a function `fn` and returns a function that guards invocation of
* `fn` such that `fn` can only ever be called once, no matter how many times
* the returned function is invoked. The first value calculated is returned in
* subsequent invocations.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (a... -> b) -> (a... -> b)
* @param {Function} fn The function to wrap in a call-only-once wrapper.
* @return {Function} The wrapped function.
* @example
*
* const addOneOnce = R.once(x => x + 1);
* addOneOnce(10); //=> 11
* addOneOnce(addOneOnce(50)); //=> 11
*/
var once = _curry1(function once(fn) {
var called = false;
var result;
return _arity(fn.length, function() {
if (called) {
return result;
}
called = true;
result = fn.apply(this, arguments);
return result;
});
});
export default once;