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

new for generator does do something useful #301

Closed
ghost opened this Issue Jan 20, 2016 · 2 comments

Comments

Projects
None yet
2 participants
@ghost

ghost commented Jan 20, 2016

RE: https://github.com/tc39/tc39-notes/blob/master/es7/2015-07/july-28.md#67-new--generatorfunction

Actually you can do this :

function *crank() {
    const next = x => this.next( x ),
          turn = x => setTimeout( () => next( x ), 100 );

   let x = 1;
   while( true ) console.log( x = x < 12 ? yield turn( x + 1 ) : yield turn( 1 ) );
}

Having a reference to itself, allows the generator to yield control flow to other operation, before returning to itself and continue processing.

This is useful.

const count = new crank();
count.next(); // yay!

Without [[construct]] trap for generators this is required:

function *crank() {
    const my = yield 'MPs EYE BAN ON NEW FOR COROUTINES AS CONSIDERED "HARMFUL"',
        next = x => my.next( x ),
        turn = x => setTimeout( () => next( x ), 100 );

   let x = 1;
   while( true ) console.log( x = x < 12 ? yield turn( x + 1 ) : yield turn( 1 ) );
}

const inconvenient = crank();
inconvenient.next();
// harmful you say?
inconvenient.next( inconvenient ); // qed
@claudepache

This comment has been minimized.

Show comment
Hide comment
@claudepache

claudepache Jan 20, 2016

Contributor

Just use a wrapper.

function start_counter() {

    function* crank() {
        const next = x => count.next( x ),
              turn = x => setTimeout( () => next( x ), 100 );

       let x = 1;
       while( true ) console.log( x = x < 12 ? yield turn( x + 1 ) : yield turn( 1 ) );
    }

    const count = crank();
    count.next(); 
}

start_counter(); // implementation details hidden: no "new", no "next"

Anyway, that sort of discussion should go to the es-discuss mailing list.

Contributor

claudepache commented Jan 20, 2016

Just use a wrapper.

function start_counter() {

    function* crank() {
        const next = x => count.next( x ),
              turn = x => setTimeout( () => next( x ), 100 );

       let x = 1;
       while( true ) console.log( x = x < 12 ? yield turn( x + 1 ) : yield turn( 1 ) );
    }

    const count = crank();
    count.next(); 
}

start_counter(); // implementation details hidden: no "new", no "next"

Anyway, that sort of discussion should go to the es-discuss mailing list.

@domenic

This comment has been minimized.

Show comment
Hide comment

@domenic domenic closed this Jan 20, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment