DEV Community

loading...

Discussion on: Infinite Data Structures & Lazy Evaluation in JavaScript

Collapse
aminnairi profile image
Amin Author • Edited

You could have an asynchronous generator function that cycle through all users in an API like JSONPlaceholder. This data structure is theoretically infinite because you don't know how many users are included in this API (well, in fact you can, but let's pretend).

So you could build a generator to return a promise listing all users. With the for-await loop, you could search for a specific user. This is great because it reduces the amount of memory needed to store the users.

"use strict";

async function* users() {
    let index = 1;

    while (true) {
        const response = await fetch(`https://jsonplaceholder.typicode.com/users/${index}`);

        if (!response.ok) {
            break;
        }

        const user = await response.json();

        yield user;

        index++;
    }
}

async function main() {
    for await (const user of users()) {
        if (user.email.includes("net")) {
            console.log(`${user.name} is a .NET user... Just kidding :)`);
            break;
        }
    }
}

main();

In this example, I have only fetched 3 users before finding the one I'm interested in. Whereas with a simple array, you would have requested for the entire database. Then you would have cycled through all of them, only to find that you needed the third one, leaving thousands in memory for nothing. This might not be the best case to illustrate what I'm trying to explain but generator functions are best to describe infinite data structures that would normally overflow the memory, or in the best case slow down the app a lot.

Forem Open with the Forem app