FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Make Counter II

20mins

Implement a function makeCounter(initialValue) that returns a counter object which can be used to retrieve and manipulate the counter.

The function should:

  • Accept an optional initial value (default is 0).
  • Return an object containing:
    • value(): returns the current counter value.
    • increment(): increases the counter by 1.
    • decrement(): decreases the counter by 1.
    • reset(): resets the counter to the initial value.
    • set(val): sets the counter to a specified number.

Example

const counter = makeCounter(5); counter.value(); // 5 counter.increment(); counter.value(); // 6 counter.decrement(); counter.value(); // 5 counter.set(10); counter.value(); // 10 counter.reset(); counter.value(); // 5

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests