📜 ⬆️ ⬇️

Streams.js: deferred (lazy) calculations in Javascript

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

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

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

The idea of ​​the supposedly "infinite" range simplifies programming. For example, a list of even and odd numbers is displayed in this way.

 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 specified parameters is possible with the help of new Stream( head, functionReturningTail ) . For example, here is a concise way for a list of 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 a “new data structure” for JavaScript.

The streams.js library on CoffeeScript: coffeestream .

Source: https://habr.com/ru/post/128264/


All Articles