The task is to implement the once() function, which is used to force a function to be called only once, later calls only returns the result of first call.
The boilerplate code:
function once(func) {
// your code here
}
Create a variable to keep track of whether the function has been called or not.
let called = false;
Create a variable to store the result of the first call, so that later calls can recall the same value
let result;
If the function isn't executed, let it run
return function(...args) {
if (!called) {
result = func.apply(this, args);
called = true;
}
return result;
};
.apply(this, args ensures that the function keeps the correct context and accepts as many arguments as possible.
The final code
function once(func) {
// your code here
let called = false;
let result;
return function(...args) {
if(!called) {
result = func.apply(this, args);
called = true;
}
return result;
}
}
That's all folks!
Top comments (0)