Last active
May 1, 2016 14:18
-
-
Save raganwald/cdfbd4c7b8aaf75469e2b404892718df to your computer and use it in GitHub Desktop.
Naïve Sieve of Eratosthenes
This file contains hidden or 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 * nullEveryNth (skipFirst, n, iterable) { | |
| const iterator = iterable[Symbol.iterator](); | |
| yield * take(skipFirst, iterator); | |
| while (true) { | |
| yield * take(n - 1, iterator); | |
| iterator.next(); | |
| yield null; | |
| } | |
| } | |
| function * sieve (iterable) { | |
| const iterator = iterable[Symbol.iterator](); | |
| let n; | |
| do { | |
| const { value } = iterator.next(); | |
| n = value; | |
| yield n; | |
| } while (n == null); | |
| yield * sieve(nullEveryNth(n * (n - 2), n, iterator)); | |
| } | |
| const Primes = compact(sieve(range(2))); | |
| // General-Purpose Lazy Operations | |
| function * range (from = 0, to = null) { | |
| let number = from; | |
| if (to == null) { | |
| while (true) { | |
| yield number++ | |
| } | |
| } | |
| else { | |
| while (number <= to) { | |
| yield number++; | |
| } | |
| } | |
| } | |
| function * take (numberToTake, iterable) { | |
| const iterator = iterable[Symbol.iterator](); | |
| for (let i = 0; i < numberToTake; ++i) { | |
| const { done, value } = iterator.next(); | |
| if (!done) yield value; | |
| } | |
| } | |
| function * compact (list) { | |
| for (const element of list) { | |
| if (element != null) { | |
| yield element; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment