DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 76

The task is to implement a count property that increments every time count is accessed.

The boilerplate code:

function createCounter(): {count: number } {
  // your code here

}
Enter fullscreen mode Exit fullscreen mode

When the count is accessed the first time, the getter is expected to return 0. So the initial state before the first access should be -1

let current = -1;
Enter fullscreen mode Exit fullscreen mode

To increment count every time it is accessed, increase the value of current

return {
 get count() {
  current++;
  return current;
 }
}
Enter fullscreen mode Exit fullscreen mode

Since a getter is being used, it cannot be increment manually i.e obj.count = 10 will fail.

The final code

function createCounter(): {count: number } {
  // your code here
  let current =  -1;

  return {
    get count() {
      current++;
      return current;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)