4

Anyone here use generator functions in JS? Seems like it could be useful but whenever I explore the possibility of using one, I usually end up going another route

Comments
  • 1
    For me it's the same with generator functions in every language. Sounds nice but never had the Real life use case for it.
  • 1
    I used generator to calculate possibly infinite series of recurring event occurences. It seemed like a good solution.
  • 1
    I've used them when I have sequences I want to iterate over and the sequence can be mathematically defined by a parameter(s).

    But in the end, it's just syntactic sugar (tho it may have different implications in other js engines) for a loop.
  • 3
    - Tokenization

    - splitting up procressing steps of arrays into many small actions that can be done one at a time

    With hack pipes this will be a lot more readable as well..
  • 2
    @CoreFusionX It literally pauses the execution of the function with every yield and preserves the state, so more than syntax sugar ..
  • 3
    function * previousIds ( lastestId ){

    while ( true )

    yield lastestId--

    }

    async function * previousComments ( latestId ){

    for ( const id of previousIds(latestId) )

    yield await

    fetch(`stuff.com/comments?id=${ latestId }`)

    .then((response) => response.json())

    }

    async function * take ( generator , limit ){

    for await ( const item of generator ){

    if(limit < 1)

    return

    yield item

    limit--;

    }

    }

    function toComment ( json ){

    const element = document.createElement('div');

    element.innerText = json.content;

    return element

    }

    for await ( const comment of previousComments(lastedId) )

    html_comments.appendChild(toHtml(comment));

    Could be much nicer with hack pipes..

    https://proposals.es/proposals/...

    Thanks devRant for removing my identation, who needed it anyways ..
  • 1
    @ElectroArchiver devRant needs support for code blocks badly
  • 1
    @Lensflare Brought this up before and SOME people didn't see the point in it..
  • 0
    The resentment is palpable 😅
Add Comment