For more tips like this, sign up to the weekly newsletter!
Generate all whole numbers
It is fairly easy to make a lazy sequence that generates all whole numbers from the natural numbers, especially with ImmutableJs.
As a recap, the sequence of natural numbers is [0, 1, 2, 3, ...]
, while that of whole numbers is [0, 1, -1, 2, -2, 3, -3, ...]
.
It is useful in situations for example when you need to find the nearest value and need the minimal amount of trials. For example, let's find the nearest prime to a given number!
To convert a Range of natural number to a Range of whole numbers, use a map
:
const wholeNums = Immutable.Range().map((n) => n % 2 === 0 ? -1 * (n / 2) : (n + 1) / 2);
Then to use it to find the nearest prime:
const nearestPrime = (num) => wholeNums.map((n) => n + num).find((n) => isPrime(n))