Write makeCounter(start): a counter with increment, decrement, reset, and value methods and private state.
makeCounter(start) returns a counter object whose count begins at start. start defaults to 0.
increment() and decrement() change the count by one and return the new count. reset() sets the count back to start and returns it. value() returns the count.
Each counter keeps its own count, and the count must not be reachable as a property of the counter.
function makeCounter(start = 0) {
// your code
}
// const counter = makeCounter(5);
// counter.increment(); // 6
// counter.increment(); // 7
// counter.decrement(); // 6
// counter.reset(); // 5
// counter.value(); // 5
// counter.count; // undefined: the count isn't a property
Solve it in the editor, with tests
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…