Skip to content

Instantly share code, notes, and snippets.

@alekpopovic
Forked from freddi301/dsl.ts
Created February 16, 2021 23:56
Show Gist options
  • Save alekpopovic/77669320de138799c5cab8ad3461d861 to your computer and use it in GitHub Desktop.
Save alekpopovic/77669320de138799c5cab8ad3461d861 to your computer and use it in GitHub Desktop.
Typescript example DSL
interface MyProgramDSL<T> {
read: () => Promise<string>;
write: (value: string) => Promise<void>
done: (value: T) => Promise<T>
}
const MyProgram = async ({ read, write, done }: MyProgramDSL<string>) => {
await write("Hello, what is your name?");
const name = await read();
return done(`Your name: ${name}, has ${name.length} letters.`);
}
const promptAlertInterpreter = <T>() => ({
read: async () => prompt(),
write: async (value: string) => alert(value),
done: async (value: T) => value
});
class PlatformConsoleInterpreter<T> implements MyProgramDSL<T> {
async read() { return navigator.platform }
async write(value) { console.log(value) }
async done(value) { return value }
}
MyProgram(promptAlertInterpreter<string>()).then(alert);
MyProgram(new PlatformConsoleInterpreter).then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment