DEV Community

DR
DR

Posted on

#2620: Counter

Back again with the second problem in the 30 Days challenge, #2620.

Process

The instructions read as follows.

Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).

Here's the unit tests, if you're curious about the return values.

const counter = createCounter(10)
counter() // 10
counter() // 11
counter() // 12
Enter fullscreen mode Exit fullscreen mode

Welcome to an important JS concept known as closures. Say we have the following function.

function outerFunction() {
  let outerVariable = 'I am outside!';

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

let closure = outerFunction();
closure(); // Outputs: "I am outside!"
Enter fullscreen mode Exit fullscreen mode

Here's the key concept - we're still able to access the outerVariable variable even though the function has finished executing. This means that to solve this problem, it's nothing harder than creating a private counter variable and incrementing it every time the function is called.

Let's write some code.

function createCounter(n) {
  let i = -1;
  return function() {
    i++;
    return n + i;
  };
}
Enter fullscreen mode Exit fullscreen mode

This was my original solution - but I'm looking back over it realizing that it's pretty messy. Let's try to simplify.

First thing - we don't need the i++ and n + i to be separate bits. I had forgotten that i++ doesn't just increment i - it returns the old value as well (if you want the new value, use ++i). So let's change that and add some arrow syntax.

function createCounter(n) {
  let i = 0;
  return () => n + i++;
}
Enter fullscreen mode Exit fullscreen mode

Note that I changed the initial value of i from -1 to 0. This is because originally we had to increment then return the number - the first time it had to be n, so we set i to -1 knowing that when we called the function the first time it would equal to n and not n + 1. With i++, it'll return n the first time - so if we kept i at -1 we'd get n-1, which is not the result we want.

Conclusion

With knowledge of closures, this one isn't that hard. This concept is another one that keeps coming out in the challenges, so make sure you're rock-solid on the concept before moving on.

If you found this helpful, be sure to leave a 💖 on the post and a ⭐ on the Github repo!

Follow for more LC content :)

Top comments (0)