infinity.js
Infinite sequences for Node.js
Supports typical array functions and more, all evaluated lazily.
Joint effort of Andrew Jones, Maxim Filimonov, Leonardo Borges and Romain Prieto, during a ThoughtWorks Node.js hack night.
Generators
infinite = require 'infinity' infiniterange 9 # naturals from 9 to infinity infinitecycle 123# repeats 1, 2, 3 forever infiniteiteration 2 i*2 # all powers of 2 infinitezip s1s2s3 # a steam pairing all given streams 1 to 1 infinitecons 9998stream # a new stream starting with the given fixed values infinitefromArray 368# this one is actually finite, but still lazy infiniteprimes # sequence of prime numbers infinitefibonacci # fibonacci sequence
Operations
These operations create a new lazy stream:
stream = infiniterange 1 streamfilter i%2 == 0 # a new stream with even numbers only streammap i*2 # a new stream with all elements doubled streamskip 2 # a new stream that starts 2 elements further streamtakeWhile i < 5 # a finite stream that stops at the given condition
And these ones resolve a stream (non lazy):
# get the first 5 elements as a javascript array streamtake 5 # reduce the stream to a single value # can only be called on a finite stream (after takeWhile) = acc + istreamreduce 0sum
Example
FizzBuzz that doesn't use loops or modulo:
naturals = infiniterange 1threes = infinitecycle ''''' fizz'fives = infinitecycle ''''''''' buzz'= arrjoin ''infinitezipnaturalsthreesfivesmapconcattake20
Custom streams
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 stailskip1 skipperinfinitefibonaccitake 5# [ 0, 1, 3, 8, 21 ]
This can be used to implement interesting algorithms.
For example, here's the implementation of infinite.primes()
:
= -> = h = shead infinitestream -> h-> sieve stailfilter x % h isnt 0 sieveinfiniterange 2 infiniteprimestake 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