Skip to content

Instantly share code, notes, and snippets.

@sdellysse
Last active October 7, 2022 16:38
Show Gist options
  • Save sdellysse/07b5dba021a8474983c3a4b7be407869 to your computer and use it in GitHub Desktop.
Save sdellysse/07b5dba021a8474983c3a4b7be407869 to your computer and use it in GitHub Desktop.
// When a for-$X construct is created, two new constructs are allowed within
// the loop body: `continue with` and `break with`. `continue with` is the equivalent
// of `return` in `fn` in something like Array.prototype.map(fn). `break with` is
// similar, but it stop further iterations of the loop.
// When a for-$X construct is given a single expression instead of a block
// as the loop body, the value of the expression is wrapped with an implicit
// `continue with`
const cases = {};
cases["for-map-of/block/continue-with-"] = () => {
const value = for map (const item of [1, 2, 3]) {
if (item % 2 === 0) {
continue with item * 2;
}
continue with `${item * item}`;
};
assert.deepEqual(value, [`1`, 4, `9`];
};
cases["for-map/block/break-and-lack-continue"] = () => {
const value = for map (let i = 0; i < 5; i++) {
if (i === 3) {
break with 3;
}
if (i % 2 === 0) {
continue with `${i} is even`;
}
};
assert.deepEqual(value, ["0 is even", undefined, "2 is even", 3]);
};
cases["for-reduce-of/block"] = () => {
const value = for reduce (const item of [1,2,3,4]; let acc = 0) {
continue with acc + item;
};
assert.equal(value, 10);
};
cases["for-reduce-of/expression"] = () => {
const value = for reduce (const item of [1,2,3,4]; let acc = 0) acc + item;
assert.equal(value, 10);
};
cases["for-reduce/expression/range"] = () => {
const value = for reduce (let i = 1; i <= 4; i++; let acc = 0) acc + i;
assert.equal(value, 10);
};
// Note that this still allows for the rarely-used feature of `continue :label` and
// `break :label`
cases["for-map/block/break-label"] = () => {
let value = null;
outerLoop: for (const item of [1,2,3]) {
innerLoop: const loopVal = for map (let i = 0; i < item; i++) {
value = i;
break outerLoop;
};
}
assert.equal(value, 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment