dtao / lazy.js

Like Underscore, but lazier

Home Page:http://danieltao.com/lazy.js/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

memoize eagerly evaluates more than necessary

fenduru opened this issue · comments

When memoizing a sequence, accessing any value in that sequence seems to cause the entire sequence to be evaluate eagerly. I think that the correct behavior would be to evaluate only what is needed on demand, and cache that value for future accesses.

My use case is that I have a very large set of data that I display as a grid. I want to lazily perform operations on the data, and then use either slice or drop/take to compute only the data that is currently in view. Then when the user scrolls, I want to slice into the memoized sequence again, avoiding recomputation of items that have already been computed.

Before memoization, it seems like some of the optimizations I'm looking for are implemented (i.e. .get(1) on a mapped array doesn't call the map function for index 0).

function double(x) {
  console.log('doubling', x);
  return x * 2;
}

var seq = Lazy([1, 2]).map(double);

seq.get(1)
// 'doubling 2'

seq.memoize().get(1)
// 'doubling 1'
// 'doubling 2'

I think I buy that. I'll take a look into how hard this would be.

@dtao This is definitely an improvement, however if I'm reading that commit correctly, it won't actually solve the test case in my original issue. seq.memoize().get(1) will still output doubling 1 unnecessarily

@fenduru You're right. I do not currently have a special case for array-like memoized sequences. memoize() now only iterates as far as necessary to get to the desired value.

I get now what you're asking for; it will just require some more time.