DEV Community

loading...

Log all Prime Numbers till `n` using Javascript Generators

Santosh Viswanatham
An open web philanthropist | Mozilla Tech Speaker | Senior Development Engineer at Pramati
Originally published at Medium on ・2 min read

Photo by freddie marriage on Unsplash

I was interviewing with few companies a couple of months back for a Frontend/Fullstack position. One of the most interesting questions I faced in one of the coding exams was to Write a function in JavaScript that takes an input 'n' and return all the prime numbers until 'n'. The question is simple and straight forward as you see it.

I quickly wrote the following code and it worked perfectly!

BOOM! I’m done. I felt happy and ran the test cases. Of course, they failed. Happiness is a myth in Javascript. There was a trick here and this was the provided main method that calls my function…

function main() {
  const primeNumberGenerator = getAllPrimeNumbers(23);
  let primeNumber;
  while ((primeNumber = primeNumberGenerator.next().value) !== undefined) {
    console.log(primeNumber);
  }
}
Enter fullscreen mode Exit fullscreen mode

I observed some new keywords like next(), I remember to have seen something similar to this in RxJS but this was a pure Javascript code so this should mean something different. I googled and found something new in Javascript that I have rarely used/heard before - Generators in Javascript. It was a timed test, so I quickly read through articles, examples and fixed my code.

It worked and all tests passed!

Generators can return (“yield”) multiple values, one after another, on-demand. They work great with [iterables](https://javascript.info/iterable), allowing to create data streams with ease.
Enter fullscreen mode Exit fullscreen mode

I don’t want to talk more about generators as there are better articles that do this. I have attached a few at the end that helped me in this course of learning.

This was one of the most interesting things I got to solve as part of the interviews. I wrote code to solve a simple problem but with lazy evaluation and memory efficiency. This was fun.

Few Articles that helped me to quickly understand Generators and Iterators -

I hope this was helpful to you to explore how we can use generators in our everyday code.

Discussion (1)

Collapse
freakomonk profile image
freakomonk

! == undefined check is redundant here, no?