Last active
January 19, 2020 20:00
-
-
Save pravdomil/c201e59fa9c7f35b53ac134a020bc149 to your computer and use it in GitHub Desktop.
Elm runtime in TypeScript
This file contains hidden or 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
export type List<A> = Array<A> | |
export type Maybe<A> = A | null | |
export type Cmd<Msg> = Maybe<(_: sendMsg<Msg>) => void> | |
type updateFn<Msg, Model> = (_: Msg) => (_: Model) => [Model, Cmd<Msg>] | |
type sendMsg<Msg> = (_: Msg) => void | |
export let elmTsRuntime: <Msg, Model>(_: [Model, Cmd<Msg>]) => (_: updateFn<Msg, Model>) => void | |
elmTsRuntime = ([model, cmd]) => update => { | |
const sendMsg = (msg: any) => { | |
try { | |
;[model, cmd] = update(msg)(model) | |
deferRun(sendMsg)(cmd) | |
} catch (e) { | |
console.error("Update error", e) | |
} | |
} | |
deferRun(sendMsg)(cmd) | |
} | |
export let cmdBatch: <Msg>(_: List<Cmd<Msg>>) => Cmd<Msg> | |
cmdBatch = cmds => sendMsg => { | |
cmds.forEach(runCmd(sendMsg)) | |
} | |
let runCmd: <Msg>(_: sendMsg<Msg>) => (_: Cmd<Msg>) => void | |
runCmd = sendMsg => cmd => { | |
try { | |
if (cmd) cmd(sendMsg) | |
} catch (e) { | |
console.error("Command error", e) | |
} | |
} | |
let deferRun: <Msg>(_: sendMsg<Msg>) => (_: Cmd<Msg>) => void | |
deferRun = sendMsg => cmd => { | |
setTimeout(() => runCmd(sendMsg)(cmd)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment