Last active
November 3, 2021 16:39
-
-
Save francisrstokes/a69fb9d3113d4688229ec04a8696c914 to your computer and use it in GitHub Desktop.
Game-style DSL using generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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