Skip to content

Instantly share code, notes, and snippets.

@francisrstokes
Last active November 3, 2021 16:39
Show Gist options
  • Save francisrstokes/a69fb9d3113d4688229ec04a8696c914 to your computer and use it in GitHub Desktop.
Save francisrstokes/a69fb9d3113d4688229ec04a8696c914 to your computer and use it in GitHub Desktop.
Game-style DSL using generators
const getDSLValue = (iterator, last) => {
const {value, done} = iterator.next(last);
if (done) {
return value;
}
switch (value) {
case 'sword': {
return getDSLValue(iterator, {
weaponType: "Shiny Sword",
damage: 10
});
}
case 'sponge': {
return getDSLValue(iterator, {
weaponType: "Greasy Sponge",
damage: 1
});
}
default: {
throw new Error('unrecongised command in DSL');
}
}
}
const dsl = gen => getDSLValue(gen());
const finalWeapon = dsl(function*() {
const w1 = yield 'sword';
const w2 = yield 'sponge';
console.log(`You pick up a ${w1.weaponType} and a ${w2.weaponType}!`);
return w1;
});
console.log(finalWeapon);
// -> You pick up a Shiny Sword and a Greasy Sponge!
// -> { weaponType: "Shiny Sword", damage: 10 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment