Trying to create this. Can someone assist?

487 views Asked by At

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
1

There are 1 answers

2
junvar On

Instead of using a function makeCounter(), I suggest just using the new operator. The # prefix to the value class field makes it private.

class Counter {
  #value
  constructor(value = 0) {
    this.#value = value;
  }
  value() {
    return this.#value;
  }
  increment() {
    this.#value++;
  }
  decrement() {
    this.#value--;
  }
}

let counter = new Counter(3);
console.log(counter.value());
counter.increment();
console.log(counter.value());