DEV Community

Santosh Viswanatham
Santosh Viswanatham

Posted on • Originally published at Medium on

Log all Prime Numbers till `n` using Javascript Generators

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!

const isPrimeNumber = (number) => {
// program to check if a number is prime or not
for (let i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
};
function getAllPrimeNumbers(number) {
let primeNumbers = [];
for (let i = 2; i <= number; i++) {
if (isPrimeNumber(i)) primeNumbers.push(i);
}
return primeNumbers;
}
console.log(getAllPrimeNumbers(23));

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.

const isPrimeNumber = (number) => {
// program to check if a number is prime or not
for (let i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
};
function* getAllPrimeNumbers(number) {
for (let i = 2; i <= number; i++) {
if (isPrimeNumber(i)) yield i;
}
}
function main() {
const primeNumberGenerator = getAllPrimeNumbers(23);
let primeNumber;
while ((primeNumber = primeNumberGenerator.next().value) !== undefined) {
console.log(primeNumber);
}
}
main();

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (1)

Collapse
 
freakomonk profile image
freakomonk

! == undefined check is redundant here, no?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs