Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow {#each} to work with generators #8467

Closed
mkmoisen opened this issue Apr 9, 2023 · 1 comment
Closed

Allow {#each} to work with generators #8467

mkmoisen opened this issue Apr 9, 2023 · 1 comment

Comments

@mkmoisen
Copy link

mkmoisen commented Apr 9, 2023

Describe the problem

I want to be able to use generator functions with the {#each} directive. Today, {#each} only allows arrays, so in order to use generator functions, I need to first convert it to an array.

Instead of writing functions that return arrays:

function columns(row) {
    const keys = [];

    for (let key of Object.keys(row)) {
        // additional logic here
        keys.push(key)
    }

    return keys;
}

I'de rather use generators to save two lines of code, making the code cleaner, as well as potentially reducing memory use.

function* columns(row) {
    for (let key of Object.keys(row)) {
        // additional logic here
       yield key
    }
}

However, today when you use a generator with the {#each} directive, it fails with:

Error: {#each} only iterates over array-like objects. You can use a spread to convert this iterable into an array.

Describe the proposed solution

Svelte could simply allow either array or generators, and loop over a generator object.

Alternatively, Svelte could check if the object being passed into the {#each} directive is a generator, and if so, automatically convert it to an array. This isn't ideal as it is not necessary to convert it to an array.

Alternatives considered

The alternative is for the programmer to manually convert the generator into an array.

This isn't exactly difficult, but it is noisy:

{#each [...columns(row)] as column}
    // ...
}

Compared to:

{#each columns(row) as column}
    // ...
}

### Importance

would make my life easier
@gtm-nayan
Copy link
Contributor

Duplicate of #7425

@dummdidumm dummdidumm closed this as not planned Won't fix, can't repro, duplicate, stale Apr 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants