Can someone assist with this query below?
In JavaScript, define a function makeCounter which takes one optional argument defining the intial value, start, with a default value of 0. The function should return an object containing keys that define 3 methods:
- value returns the current value of the counter
- increment increments the value of the counter by 1 and returns the new value
- decrement decrements the value of the counter by 1 and returns the new value
The returned object should not allow direct modification or retrieval of the value.
Example usage:
var counter = makeCounter();
console.log(counter.value());
// 0
var counter2 = makeCounter(4);
console.log(counter2.value());
// 4
console.log(counter2.increment());
// 5
console.log(counter2.value());
// 5
counter2.decrement();
counter2.decrement();
console.log(counter2.decrement());
// 2
Instead of using a function
makeCounter(), I suggest just using thenewoperator. The#prefix to thevalueclass field makes it private.