Created
February 7, 2020 13:36
-
-
Save briancavalier/bb246888ddeb6559a14333d150cc1ecd to your computer and use it in GitHub Desktop.
Two ways to use Env
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
import { co, unsafeRun, resumeLater, resumeNow, use, Resume, op } from '../src' | |
import { EOL } from 'os' | |
import { createInterface } from 'readline' | |
type Print = { print(s: string): Resume<void> } | |
const print = (s: string) => op<Print>(c => c.print(s)) | |
type Read = { read(): Resume<string> } | |
const read = op<Read>(c => c.read()) | |
const main = co(function* () { | |
while(true) { | |
yield* print('> ') | |
const s = yield* read | |
yield* print(`${s}${EOL}`) | |
} | |
}) | |
const capabilities = { | |
print: (s: string): Resume<void> => | |
resumeNow(void process.stdout.write(s)), | |
read: (): Resume<string> => | |
resumeLater(k => { | |
const handler = (s: string): void => { | |
readline.close() | |
k(s) | |
} | |
const readline = createInterface({ input: process.stdin }).once('line', handler) | |
return () => readline.removeListener('line', handler).close() | |
}) | |
} | |
const m = use(main(), capabilities) | |
unsafeRun(m) |
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
import { co, unsafeRun, resumeLater, resumeNow, use, op } from '../src' | |
import { EOL } from 'os' | |
import { createInterface, Interface } from 'readline' | |
type Console = { stdout: typeof process.stdout } | |
const print = (s: string) => op<Console, void>(c => resumeNow(void c.stdout.write(s))) | |
type Readline = { readline: Interface } | |
const read = op<Readline, string>(c => resumeLater(k => { | |
c.readline.once('line', k) | |
return () => c.readline.removeListener('line', k) | |
})) | |
const main = co(function* () { | |
while (true) { | |
yield* print('> ') | |
const s = yield* read | |
yield* print(`${s}${EOL}`) | |
} | |
}) | |
const environment = { | |
stdout: process.stdout, | |
readline: createInterface({ input: process.stdin }) | |
} | |
const m = use(main(), environment) | |
unsafeRun(m) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment