arogozine / LinqToTypeScript

LINQ to TypeScript
https://arogozine.github.io/linqtotypescript/
MIT License
139 stars 18 forks source link

one shot queries #14

Closed levnach closed 3 years ago

levnach commented 3 years ago

Hi there! It looks like some queries are 'one shot' queries. They are not reusable. For example the following test passes. test('ienum', () => { function* foo() { yield 0 } const e = from(foo()) expect(e.count()).toBe(1) expect(e.count()).toBe(0) }) Please notice that the first call to e.count() returns 1 as the second returns 0! Is it by design?

arogozine commented 3 years ago

I think that makes sense. You can only go forward with an iteration. So the first count iterates through all the values, giving nothing to iterate over for the second call to count.

In the next release (see dev branch) you should be able to do the following,

function* foo() { yield 0 }
const e2 = from(foo)
console.log(e2.count())
console.log(e2.count())
levnach commented 3 years ago

Sorry, your comment is not clear for me. Do you expect to get 1 at the second printout? I noticed that you used foo without (). Do you expect output 1 in both cases? It would be great.

arogozine commented 3 years ago

No to the first question. The iterator given by foo() can only move forward. So the first count() iterates through all the elements and gives the correct number but the second count() has nothing to iterate over so the number is 0. The library does not cache anything.

Yes to the second question. With the upcoming release - you can pass in the generator function itself - not the iterator given by the function - thus each count() calls foo() resulting in both being 1

Currently if you want to go from a generator, I'd suggest converting to an array [...foo()]

arogozine commented 3 years ago

I did a quick release that should allow passing in generator functions - like from(foo)

levnach commented 3 years ago

It seems working, thanks!