DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 76

The task is to implement a count function that returns how many times it is called.

Create the function and initialise the variable that records how many times the function is called.

function counter () {
 let calls = 0;
}
Enter fullscreen mode Exit fullscreen mode

Implement the count function

function count(): number {
calls++;
return calls
}
Enter fullscreen mode Exit fullscreen mode

A function to reset the number of calls is also needed

count.reset = () => {
calls = 0;
}
Enter fullscreen mode Exit fullscreen mode

The number of counts should be returned

return count
Enter fullscreen mode Exit fullscreen mode

There should be a function that calls the counter

const count = counter();
Enter fullscreen mode Exit fullscreen mode

The final code

function counter () {
  let calls = 0;

  function count(): number {
    calls++;
    return calls;
  }

  count.reset = () => {
    calls = 0;
  }

  return count;
}

const count = counter()
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)