I want to write a function once that accepts a callback as input and returns a function. When the returned function is called the first time, it should call the callback and return that output. If it is called any additional times, instead of calling the callback again it will simply return the output value from the first time it was called.
Below is what I have tried to do. But I am not getting the results as I expected. I need to understand this concept.
function once(func) {
let num;
function retFunc(x){
num = func(x);
return num;
}
return retFunc;
}
function addByTwo(input){
return input + 2;
}
var onceFunc = once(addByTwo);
console.log(onceFunc(4)); //should log 6
console.log(onceFunc(10)); //should log 6
console.log(onceFunc(9001)); //should log 6
numis already a good first step, but how do you remember that it was called a first time already? You always overwritenum = func(x)