2/5/20

Generators OR Interesting question i was asked at some interview

Question

Recently im going a lot to various interviews. So here is one interesting question i was asked:
Can you write the "adder" function that can be called multiple times and return sum of all numbers passed so far?
Example:
adder(1) // 1
adder(4) // 5
adder(2) // 7
Yes i answered, it is easy:


let store = 0;
function adder(num) {
  return store += num;
}
console.log(adder(1)) // 1
console.log(adder(6)) // 7

But interviewer asked:
And will it be possible not to use outer scope variables? (And i understood that answer is Yes)
Im not good at interviews in general, so the answer i finally got with, was:

let adder = (() => {
  let store = 0;
  return num  => store += num;
})()
console.log(adder(1)) // 1
console.log(adder(6)) // 7

Which is pretty much the same idea only the "store" is store inside the "Adder" function (actually it is more resembles the object with property to me)

Generators

After the interview (and actually even after i received a reject from this place) i had a sudden thought:what about generators - can they help me is such a problem?
What is generator?
according to the MDN site: Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.
Which sounds exactly what is needed in my case, right?
After playing around i come with following code:


function* adder() {
 let i = 0
 while(true)  {
  i += yield i;
 }
}

const gen = adder();
gen.next()
console.log(gen.next(1).value);  // 1
console.log(gen.next(2).value);  // 3
console.log(gen.next(3).value);  // 6

Which is pretty much doing the same thing, only it has very different and complicated syntax...

Conclusion

In this post i tried to show how to build a function with a "state" (statefull). I solved a problem by using a closure;
Also i asked myself if generators can be helpfull here, and although the answer was not so clear, it was yet interesting to play with generators

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...