Imagine you are developing a project that tracks different metrics. We need a counter function, but it is more complex than a regular counter. Please design a function named createCounter that optionally accepts an initial value as a parameter. This function should return a new function.
When you call this new function for the first time, it should return the initial value if provided, or the default value of 0 if not. Interestingly, each subsequent call should return a value that is incremented by 1 from the previous return value. Note that we want this behavior encapsulated within this function.
// No initial value provided
const counter = createCounter();
counter(); // 0
counter(); // 1
counter(); // 2
// Initial value provided is 10
const counter = createCounter(10);
counter(); // 10
counter(); // 11
counter(); // 12
function createCounter(initNum = 0){
let sum = initNum - 1
return function(){
sum+=1
return sum
}
}
function createCounter(initialValue = 0) {
let count = initialValue;
return () => {
return count++;
};
}