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 8b35328

Browse files
Problem 10 solved
1 parent 8765b32 commit 8b35328

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
3+
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.
4+
5+
The first time the returned function is called, it should return the same result as fn.
6+
Every subsequent time it is called, it should return undefined.
7+
8+
9+
Example 1:
10+
11+
Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
12+
Output: [{"calls":1,"value":6}]
13+
Explanation:
14+
const onceFn = once(fn);
15+
onceFn(1, 2, 3); // 6
16+
onceFn(2, 3, 6); // undefined, fn was not called
17+
Example 2:
18+
19+
Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
20+
Output: [{"calls":1,"value":140}]
21+
Explanation:
22+
const onceFn = once(fn);
23+
onceFn(5, 7, 4); // 140
24+
onceFn(2, 3, 6); // undefined, fn was not called
25+
onceFn(4, 6, 8); // undefined, fn was not called
26+
27+
28+
Constraints:
29+
30+
calls is a valid JSON array
31+
1 <= calls.length <= 10
32+
1 <= calls[i].length <= 100
33+
2 <= JSON.stringify(calls).length <= 1000
34+
35+
36+
37+
38+
39+
40+
*/
41+
42+
43+
44+
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
45+
type OnceFn = (...args: JSONValue[]) => JSONValue | undefined;
46+
47+
function once(fn: Function): OnceFn {
48+
let called = false;
49+
let rst: JSONValue;
50+
51+
return function (...args: JSONValue[]): JSONValue | undefined {
52+
if (!called) {
53+
called = true;
54+
rst = fn(...args);
55+
return rst;
56+
}
57+
return undefined;
58+
};
59+
}
60+
/**
61+
* let fn = (a,b,c) => (a + b + c)
62+
* let onceFn = once(fn)
63+
*
64+
* onceFn(1,2,3); // 6
65+
* onceFn(2,3,6); // returns undefined without calling fn
66+
*/

0 commit comments

Comments
(0)

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