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

Appearance settings

Latest commit

 

History

History
History
41 lines (38 loc) · 1.02 KB

File metadata and controls

41 lines (38 loc) · 1.02 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
// 2666. Allow One Function Call
// 🟢 Easy
//
// https://leetcode.com/problems/allow-one-function-call/
//
// Tags: Javascript
// Preserve one boolean value with internal state that determines whether the
// funcion has been called already once, when called, if it is the first call,
// return the result of calling fn with the given arguments, if it is not the
// first call, do not return anything, which is the same as explicitly
// returning undefined. Use `apply` to pass the caller's context to fn.
//
// Time complexity: O(1)
// Space complexity: O(1)
//
// Runtime 68 ms Beats 8.32%
// Memory 41.6 MB Beats 90.70%
/**
* @param {Function} fn
* @return {Function}
*/
var once = function (fn) {
let called = false;
return function (...args) {
if (!called) {
called = true;
// Preserve the caller's context.
return fn.apply(this, args);
}
};
};
/**
* 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
*/
Morty Proxy This is a proxified and sanitized view of the page, visit original site.