Another day, another LeetCode problem π€. I hope, you could solve the last problem on your own and fully understand what was happening.
Starting point
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).
My Submission
Let's take a look at my code. Yours maybe looks different, and that's okay. Everyone has their own approach.
var createCounter = function(n) {
return function() {
let m = n;
n++
return m;
};
};
What happens here?
var createCounter = function(n) {
};
What was given by LeetCode was the outer declaration, the initialization of var createCounter
, which was assigned a function that takes one argument, a number n
.
π» Note: I personally never use var
when declaring a variable, I always opt for let
or const
, but since this was the default, I'll keep it that way (there's nothing really wrong with using var
).
Return a function
In the description it is said that we should return a function, which I did by writing
return function() {
};
Initial return and increment
The first return should be the number n
itself. The next return should be one more then the number before and so on.
let m = n;
n++;
return m;
By declaring m
and giving it the value of n
, the first time we call the function the value of return m
is what is was declared in the beginning, the value of n
.
n++
, which stand for increment the number n
by 1, only happens after m
is return. So, the second time we call the function, m
will then be m + 1
.
In general, I am bad at explaining technical stuff. So any advice is welcome to improve my explanation skills ππ½.
Top comments (2)
By watching your hard work and dedication to explain the technical stuffs , inspired me to start learn in public.
Yes, do it @rifat87 πͺ