This, is probably a relatively common way of using underscore. Chaining methods is awesome, and the code is amazingly terse. The problem is, that this code is extremely wasteful. This is what happens behind the scenes:

Underscore wraps the input array in an underscore collection object.

It traverses over the entire array and maps it using func1 to create a new collection.

It traverses over the entire array and maps it using func2 to create a new collection.

It traverses over the entire array and maps it using func3 to create a new collection.

It plucks the first 5 values from the collection and returns it.

Imagine, if 'array’ had a million values in it. You just did computations on 999,995 values that you didn’t even need. Further, while you could have traversed the array just once, you actually did that three times. Once for each map function. If you were implementing the same logic without underscore, you probably would’ve done something like this:

You don’t need the chain() method, other than that, it is basically identical. As a downside, you need to call ValueOf even when you’re not chaining methods:

var newArr = Lazy(array).map(func).valueOf();

I think that’s a good compromise in the massive performance benefit.

If you’re convinced about the value of Lazy.js, you can probably choose to not read anymore. I was however, curious about how Lazy did it’s magic and am trying to implement something similar myself. I had reimplemented Underscore.js and I know what great learning experience it was. I hope, re-implementing a subset of Lazy.js will probably be super-useful too. I’m only implementing the map and pluck functionality, though, as this is little more than a learning exercise.

And that’s it. The idea is to remember what to do, but not actually do it. Here I’m adding all the map functions to an array, and using all of them in a single iteration when value() is called. Here is how you would actually use my rudimentary implementation of a subset of Lazy.js: