Skip to content

CodeNot attempted

createCounter with private state

Difficulty: easy

createCounter(init) returns { increment, decrement, reset }.

  • increment() / decrement() return the new value; reset() returns init
  • every counter is independent and its count is private (not a property)
  • methods must work even when destructured: const { increment } = createCounter(1)
Show reference solution
// Return an object that closes over `count`. Don't use `this`: in a plain function call it isn't the counter.
export function createCounter(init: number) {
let count = init;
return {
increment() {
count += 1;
return count;
},
decrement() {
count -= 1;
return count;
},
reset() {
count = init;
return count;
},
};
}
Loading editor…