Created
March 9, 2017 08:10
-
-
Save ryanzyy/756adb4c380be9f91a36fa76caf69327 to your computer and use it in GitHub Desktop.
Get Prime Numbers using JavaScript Generator [ECMAScript]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function* from(i) { while (true) { yield i; i++; } } | |
function* genFilter(gen, cond) { | |
for (let e of gen) { if (cond(e)) yield e; } | |
} | |
function* prime(gen) { | |
let head = gen.next().value; | |
yield head; | |
yield* prime(genFilter(gen, (x) => x % head !== 0)); | |
} | |
function* take(gen, num) { | |
let i = 0; | |
while (i < num) { | |
yield gen.next().value; | |
i++; | |
} | |
} | |
let primes = prime(from(2)); | |
console.log(...take(primes, 10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment