A Question on Closure with Javascript #177
-
hello everyone, so I've been given a challenge
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.
function once(func) {
let counter = 0;
let onceVal;
const innerFunc = (val) => {
if (counter === 0) {
onceVal = func(val);
}
counter++;
return onceVal;
};
return innerFunc;
}
const onceFunc = once(addByTwo);
// UNCOMMENT THESE TO TEST YOUR WORK!
// console.log(onceFunc(4)); //should log 6
// console.log(onceFunc(10)); //should log 6
// console.log(onceFunc(9001)); //should log 6 |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
function once(func) {
// Set Counter to 0
let counter = 0; // This value is static
// value returned if function is called
let onceVal; // This value is static
// declare this function
const innerFuc = val => {
// check if counter == 0
if (counter == 0) {
// if counter is 0 set the return value of function arg to onceVal
onceVal = func(val); // this function is the one passed in.
}
// increment counter
++counter;
// return value
return onceVal;
};
// if no args return inner function
// or return innerFuc(val)
return innerFuc;
}
// add value by 2
const addByTwo = val => val += 2;
const onceFunc = once(addByTwo);
console.log(onceFunc(4)); // log 6
console.log(onceFunc(6)); // log 6
console.log(onceFunc(9001)); // log 6
console.log(once()); // log innerfunction |
Beta Was this translation helpful? Give feedback.
-
see this example: function makeAdder(x) {
let result = 0; // this value becomes static -- it keeps the value in memory.
return function(y) {
result += (x + y);
return result
};
}
const add5 = makeAdder(5); // this result is set to 0
const add10 = makeAdder(10); // this result is set to 0
console.log(add5(2)); // 7 -> result is set to 7
console.log(add5(2)); // 14 -> 2 + 5 + result (aka 7) -> 14
console.log(add10(2)); // 12
console.log(add10(2)); // 24 from mozilla docs: In essence, makeAdder is a function factory. It creates functions that can add a specific value to their argument. In the above example, the function factory creates two new functions—one that adds five to its argument, and one that adds 10. add5 and add10 are both closures. They share the same function body definition, but store different lexical environments. In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10. |
Beta Was this translation helpful? Give feedback.
-
jomefavourite: When the function is called a second time the counter is greater then 0. |
Beta Was this translation helpful? Give feedback.
jomefavourite:
When the function is called a second time the counter is greater then 0.
So we don’t reassign the onceVal variable.