Skip to content

Commit

Permalink
Merge pull request #109 from facebook/return-method
Browse files Browse the repository at this point in the history
Implement generator.return(argument) method for closing generators.

Now officially part of the ES6 spec: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generator.prototype.return
  • Loading branch information
benjamn committed Aug 17, 2014
2 parents b6d36f9 + 46f47f1 commit 6c0ae98
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
4 changes: 4 additions & 0 deletions runtime/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@
method = "next";
arg = undefined;
}

} else if (method === "return") {
context.abrupt("return", arg);
}

state = GenStateExecuting;
Expand Down Expand Up @@ -182,6 +185,7 @@

generator.next = invoke.bind(generator, "next");
generator.throw = invoke.bind(generator, "throw");
generator.return = invoke.bind(generator, "return");

return generator;
}
Expand Down
2 changes: 1 addition & 1 deletion runtime/min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

48 changes: 48 additions & 0 deletions test/tests.es6.js
Original file line number Diff line number Diff line change
Expand Up @@ -1797,3 +1797,51 @@ describe("for-of loops", function() {
], 6);
});
});

describe("generator return method", function() {
if (!runningInTranslation) {
// The return method has not been specified or implemented natively,
// yet, so these tests need only pass in translation.
return;
}

it("should work with newborn generators", function() {
function *gen() {
yield 0;
}

var g = gen();

assert.deepEqual(g.return("argument"), {
value: "argument",
done: true
});

assertAlreadyFinished(g);
});

it("should behave as if generator actually returned", function() {
var executedFinally = false;

function *gen() {
try {
yield 0;
} catch (err) {
assert.ok(false, "should not have executed the catch handler");
} finally {
executedFinally = true;
}
}

var g = gen();
assert.deepEqual(g.next(), { value: 0, done: false });

assert.deepEqual(g.return("argument"), {
value: "argument",
done: true
});

assert.strictEqual(executedFinally, true);
assertAlreadyFinished(g);
});
});

0 comments on commit 6c0ae98

Please sign in to comment.