Книга: Functional Programming in JavaScript
Назад: Bilby.js
Дальше: Bacon.js

Lazy.js

Lazy is a utility library more along the lines of the library but with a lazy evaluation strategy. Because of this, Lazy makes the impossible possible by functionally computing results of series that won't be available with immediate interpretation. It also boasts a significant performance boost.

The library is still very young. But it has a lot of momentum and community enthusiasm behind it.

The idea is that, in Lazy, everything is a sequence that we can iterate over. Owing to the way the library controls the order in which methods are applied, many really cool things can be achieved: asynchronous iteration (parallel programming), infinite sequences, functional reactive programming, and more.

The following examples show off a bit of everything:

// Get the first eight lines of a song's lyrics var lyrics = "Lorem ipsum dolor sit amet, consectetur adipiscing eli // Without Lazy, the entire string is first split into lines console.log(lyrics.split('\n').slice(0,3));   // With Lazy, the text is only split into the first 8 lines // The lyrics can even be infinitely long! console.log(Lazy(lyrics).split('\n').take(3));  //First 10 squares that are evenly divisible by 3 var oneTo1000 = Lazy.range(1, 1000).toArray();  var sequence = Lazy(oneTo1000)   .map(function(x) { return x * x; })   .filter(function(x) { return x % 3 === 0; })   .take(10)   .each(function(x) { console.log(x); });  // asynchronous iteration over an infinite sequence var asyncSequence = Lazy.generate(function(x){return x++})   .async(100) // 0.100s intervals between elements   .take(20) // only compute the first 20     .each(function(e) { // begin iterating over the sequence     console.log(new Date().getMilliseconds() + ": " + e);   });

More examples and use-cases are covered in , Implementing Functional Programming Techniques in JavaScript.

But its not entirely correct to fully credit the library with this idea. One of its predecessors, the library, works in much the same way.

Назад: Bilby.js
Дальше: Bacon.js

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)