Infinite sequences for Node.js
Supports typical array functions and more, all evaluated lazily.
infinite = require 'infinity'infiniterange 9 # naturals from 9 to infinityinfinitecycle 123# repeats 1, 2, 3 foreverinfiniteiteration 2 i*2 # all powers of 2infinitezip s1s2s3 # a steam pairing all given streams 1 to 1infinitecons 9998stream # a new stream starting with the given fixed valuesinfinitefromArray 368# this one is actually finite, but still lazyinfiniteprimes # sequence of prime numbersinfinitefibonacci # fibonacci sequence
These operations create a new lazy stream:
stream = infiniterange 1streamfilter i%2 == 0 # a new stream with even numbers onlystreammap i*2 # a new stream with all elements doubledstreamskip 2 # a new stream that starts 2 elements furtherstreamtakeWhile i < 5 # a finite stream that stops at the given condition
And these ones resolve a stream (non lazy):
FizzBuzz that doesn't use loops or modulo:
naturals = infiniterange 1threes = infinitecycle ''''' fizz'fives = infinitecycle ''''''''' buzz'= arrjoin ''infinitezipnaturalsthreesfivesmapconcattake20
The basic generators (range, cycle) are not always enough.... but chances are you can express your stream as a head and a tail.
- The head is a function that returns a value
- The tail is a function that returns a stream
For example the following sequence outputs every second item it's given, lazily:
= infinitestream -> sfirst-> skipper stailskip1skipperinfinitefibonaccitake 5# [ 0, 1, 3, 8, 21 ]
This can be used to implement interesting algorithms.
For example, here's the implementation of
= ->=h = sheadinfinitestream -> h-> sieve stailfilter x % h isnt 0sieveinfiniterange 2infiniteprimestake 5# [ 2, 3, 5, 7, 11 ]infiniteprimesfilter i > 1000 take 5# [ 1009, 1013, 1019, 1021, 1031 ]
Curious about the code?
Go to the folder you just cloned:
npm installnpm test