Make Counter
JavaScript
easy
15 mins
Create a function makeCounter that returns a counter object with methods to increment, decrement, and reset the counter. The counter should maintain its current value and provide these operations:
increment()– Increases the counter by 1 and returns the new value.decrement()– Decreases the counter by 1 and returns the new value.reset()– Resets the counter to its initial value (default: 0) and returns the reset value.
The counter should also allow an optional initial value.
Example Inputs & Outputs
const counter = makeCounter(5); console.log(counter.increment()); // 6 console.log(counter.increment()); // 7 console.log(counter.decrement()); // 6 console.log(counter.reset()); // 5 console.log(counter.decrement()); // 4
Constraints & Edge Cases
- The counter should handle negative initial values.
- The counter should not expose its internal value directly (encapsulation).
- Methods should be chainable (optional bonus).
Companies:
meta
google
microsoft
phonepe
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
