This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
155. create a count function
Here's one possible solution:
function count() {
var counter = 0;
return function() {
return ++counter;
}
}
count.reset = function() {
count.counter = 0;
}
var c = count();
console.log(c()); // 1
console.log(c()); // 2
console.log(c()); // 3
c.reset();
console.log(c()); // 1
console.log(c()); // 2
console.log(c()); // 3
In this solution, count()
creates a closure that holds a private counter
variable which is incremented every time the returned function is called. We then attach a reset
method to the count
function object that sets the counter
to 0. Finally, we create an instance of the count()
closure and use it to keep track of the count.