Streams.js: deferred (lazy) calculations in Javascript

    The javascript library stream.js introduces the “new” 1 structure of numerical data: stream. This is a container that looks like an array and an linked list, but contains an unlimited number of elements implemented by the deferred computing method .

    var s = Stream.range( 10, 20 );  
    s.print(); // prints the numbers from 10 to 20

    For the argument, Stream.range( low, high )you can specify only the initial boundary of the range Stream.range( low ), then the stream will consist of an unlimited number of natural numbers. The default Stream.range()starts with 1.

    The idea of ​​an allegedly “infinite” range simplifies programming. For example, a list of even and odd numbers is thus displayed.

    var naturalNumbers = Stream.range(); // naturalNumbers is now 1, 2, 3, ...  
    var evenNumbers = naturalNumbers.map( function ( x ) {  
        return 2 * x;  
    } ); // evenNumbers is now 2, 4, 6, ...  
    var oddNumbers = naturalNumbers.filter( function ( x ) {  
        return x % 2 != 0;  
    } ); // oddNumbers is now 1, 3, 5, ...  
    evenNumbers.take( 3 ).print(); // prints 2, 4, 6  
    oddNumbers.take( 3 ).print(); // prints 1, 3, 5

    Creating your own streams with the given parameters is possible with new Stream( head, functionReturningTail ). For example, here is a concise way to list natural numbers.

    function ones() {  
        return new Stream( 1, ones );  
    }  
    function naturalNumbers() {  
        return new Stream(  
            // the natural numbers are the stream whose first element is 1...  
            1,  
            function () {  
                // and the rest are the natural numbers all incremented by one  
                // which is obtained by adding the stream of natural numbers...  
                // 1, 2, 3, 4, 5, ...  
                // to the infinite stream of ones...  
                // 1, 1, 1, 1, 1, ...  
                // yielding...  
                // 2, 3, 4, 5, 6, ...  
                // which indeed are the REST of the natural numbers after one  
                return ones().add( naturalNumbers() );  
            }   
        );  
    }  
    naturalNumbers().take( 5 ).print(); // prints 1, 2, 3, 4, 5

    1 PS A similar concept of deferred computing, but with a different syntax, is implemented in linq.js and node-lazy , so it’s not quite correct for the author to call lists “the new data structure” for JavaScript.

    CoffeeScript streams.js library: coffeestream .

    Also popular now: