0

Is there any way to convert regular array into lazy enumerable? I want the code below produces only one log, not ten ones:

const items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
items.map((i) => {
    console.log('expensive process');
    return i;
  })
  .findIndex((i) => true);

2
  • To answer your question more accurately, please describe your use cases... Commented May 19, 2021 at 10:37
  • i want doing something like this const goodChild = Array.from(parent.children).filter(calculateCondition).map(c => { child: c, area: calcArea(c) })[0] Commented May 19, 2021 at 10:51

2 Answers 2

1

You can use the Array.find method to stop right after you find the right one element.

const items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];


items.find((i) => {
    if(i){
        console.log('expensive process');
    }
    
    return i;
});
Sign up to request clarification or add additional context in comments.

2 Comments

i can't do that, there are severals expensive .map & .filter before the last .find
@HeyyyMarco You can't stop .map. You can use yeild to pause and resume a generator function. You can use async/await: const arr = [1, 2, 3]; const asyncRes = await Promise.all(arr.map(async (i) => { await sleep(10); return i + 1; })); console.log(asyncRes); // 2,3,4
1

Since ECMAScript 2025 we have iterator helpers, including map and find methods, such that we get the "lazy" behaviour. For your example you can consume the map-returned iterator with find, and if its callback returns a truthy value, nothing more will be consumed from the map-returned iterator:

const items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const item = items.values().map((i) => {
    console.log('expensive process');
    return i;
})
.find((i) => true);

console.log("item is", item);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.