Created
April 14, 2022 21:03
-
-
Save suneettipirneni/1243e6beaae7d94c9935191fe81e9651 to your computer and use it in GitHub Desktop.
A simple demo of representing and using infinite sequences in JavaScript
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
import { iter } from 'iterator-helper'; | |
/** | |
* Represents a set of numbers from given start to a given end. | |
* @param start The starting number in the range (default 0) | |
* @param end The ending number in the range (default Infinity) | |
*/ | |
const numbers = (start = 0, end = Infinity) => | |
iter( | |
(function* () { | |
let i = start; | |
while (i < end) { | |
yield ++i; | |
} | |
})() | |
); | |
/** | |
* Represents the set of all fibonacci numbers. | |
*/ | |
const fib = () => | |
iter( | |
(function* () { | |
let [a, b] = [0, 1]; | |
while (true) { | |
yield a; | |
[a, b] = [b, a + b]; | |
} | |
})() | |
); | |
const add = (a: number, b: number) => a + b; | |
const double = (n: number) => n * 2; | |
const isEven = (n: number) => n % 2 === 0; | |
// Represents all even fibonacci numbers and double them. | |
const evenDoubleFib = fib().filter(isEven).map(double); | |
// Get the first 5 doubled and even primes | |
evenDoubleFib.take(5); // 0 4 16 68 288 | |
/** | |
* Detects if a number is prime or not. | |
* @param num The number to check | |
*/ | |
const isPrime = (num: number) => { | |
for (let i = 2, s = Math.sqrt(num); i <= s; i++) | |
if (num % i === 0) return false; | |
return num > 1; | |
}; | |
// Represents all prime numbers from the set of all natural numbers | |
const primes = () => numbers().filter(isPrime); | |
// Get the first 5 primes | |
primes().take(5); // 2 3 5 7 11 | |
// Represents the sum of the first N prime numbers | |
const sumPrimes = (n: number) => primes().take(n).reduce(add, 0); | |
// Sum the first 5 prime numbers | |
sumPrimes(5); // 28 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
🥰