-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAllowOneFunctionCall.js
More file actions
37 lines (31 loc) · 877 Bytes
/
AllowOneFunctionCall.js
File metadata and controls
37 lines (31 loc) · 877 Bytes
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
// Given a function fn, return a new function that is identical
// to the original function except that it ensures fn is called at most once.
/**
* @param {Function} fn
* @return {Function}
*/
const once = function(fn) {
let functionCalled = false;
let result;
return function(...args){
if(!functionCalled){
result = fn(...args)
functionCalled = true
return result;
}else {
return undefined;
}
}
};
/**
* let fn = (a,b,c) => (a + b + c)
* let onceFn = once(fn)
*
* onceFn(1,2,3); // 6
* onceFn(2,3,6); // returns undefined without calling fn
*/
let fn = (a,b,c) => (a + b + c)
let onceFn = once(fn)
console.log(onceFn(1,2,3)) // 6
console.log(onceFn(2,3,6)) // returns undefined without calling fn
console.log(onceFn(2,3,6)) // returns undefined without calling fn