Skip to content

Instantly share code, notes, and snippets.

@pravdomil
Last active January 19, 2020 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pravdomil/c201e59fa9c7f35b53ac134a020bc149 to your computer and use it in GitHub Desktop.
Save pravdomil/c201e59fa9c7f35b53ac134a020bc149 to your computer and use it in GitHub Desktop.
Elm runtime in TypeScript
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