Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2919098

Browse files
Create Allow One Function Call
1 parent 76a5682 commit 2919098

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎Allow One Function Call‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
Example 1:
3+
4+
Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
5+
Output: [{"calls":1,"value":6}]
6+
Explanation:
7+
const onceFn = once(fn);
8+
onceFn(1, 2, 3); // 6
9+
onceFn(2, 3, 6); // undefined, fn was not called
10+
*/
11+
12+
type Fn = (...args: any[]) => any
13+
14+
function once(fn: Fn): Fn {
15+
let hasBeenCalled: any = false;
16+
let result: number[];
17+
return function (...args): any | undefined {
18+
if(!hasBeenCalled){
19+
result = fn(...args);
20+
hasBeenCalled = true;
21+
return result;
22+
}else{
23+
return undefined;
24+
}
25+
};
26+
}
27+
28+
/**
29+
* let fn = (a,b,c) => (a + b + c)
30+
* let onceFn = once(fn)
31+
*
32+
* onceFn(1,2,3); // 6
33+
* onceFn(2,3,6); // returns undefined without calling fn
34+
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /