This question may apply to other languages but it is explicitly about JavaScript.
I've been trying to write a lazy evaluation implementation to filter through an array of elements. The filter process can be made up of 2 functions, F and G, that each check an element against some logic and return a Boolean that is used to determine whether or not the element will appear in the final resulting array.
This is what it would look like traditionally using the built-in methods.
const result = elements.filter(F).filter(G);
This is my first attempt at writing a lazy evaluation way of handling the same scenario WITHOUT returning intermittent arrays and calling the intermediate filter
method:
for (let i = 0; i < elements.length; i++) {
if (F(elements[i])) {
if (G(elements[i])) {
newArray.push(elements[i]);
}
}
}
Now I know my code is wonky and wrong because I've looked at other libraries that use iterators and generators. Why?
Why not use a for loop if the collection is an array? What makes it faster, if it is?
if
statements?for
loop, any method I use will not return until I iterate over the entire collection? And not sure I grok this part of your response: "rather than returning without having iterated the collection at all, and iterating the source collection as the results of the iterator you return" If you provide an answer, I'll gladly accept it as the correct one.for
loop is going to iterate the entire sequence before returning, thus making it not lazy. That's not to say that a lazy implementation cannot possibly use afor
loop. It can do whatever it wants, so long as it doesn't read in information from the source until that information is needed by the result.