Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Evaluation Not Working In Lodash

The Lodash documentation says that it supports lazy evaluation. From my testing, the below chain is being evaluated 100 times rather than 10. I'm using version 3.10.1.

_(_.range(100))
 .map(function(x) {console.log(1); return x; })
 .take(10)
 .value()

You can see that we print to the console 100 times inside map, rather than the 10 times I would have expected. Check out the problem here: https://jsfiddle.net/07utwk6y/

What am I doing wrong? How can I make this evaluate lazily?

Update: This appears to be a regression in Lodash. I tested how this works across versions and came across the following results:

Version 2.4.2: 100 times https://jsfiddle.net/4Lq7z5xL/

Version 3.0.0: 10 times https://jsfiddle.net/fd6g6un5/

Version 3.9.0 10 times https://jsfiddle.net/ju8rppee/

Version 3.10.0: 100 times https://jsfiddle.net/x1g13oo8/

like image 529
inperspective Avatar asked Aug 08 '15 05:08

inperspective


1 Answers

This is expected behavior. Lodash will only perform this optimization on arrays with 200 or more items. Increase the range to 200 in the first line to see this working.

like image 111
inperspective Avatar answered Oct 19 '22 03:10

inperspective