Created
November 9, 2022 09:40
-
-
Save cometkim/a18753a8bcefe8acbba62e8900f481a7 to your computer and use it in GitHub Desktop.
7GUIs temperature converter example in ReScript
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
<div> | |
Celcius: <input id="ce" type="number"> | |
Fahrenheit: <input id="fa" type="number"> | |
</div> | |
<script type="importmap"> | |
{ | |
"imports": { | |
"rescript/": "/node_modules/rescript/" | |
} | |
} | |
</script> | |
<script type="module"> | |
import { Program, initialState } from './temp.bs.js'; | |
let $ce = document.getElementById('ce'); | |
let $fa = document.getElementById('fa'); | |
let onUpdate = (_, nextState) => { | |
$ce.value = nextState.celsius; | |
$fa.value = nextState.fahrenheit; | |
}; | |
onUpdate(initialState, initialState); | |
let program = Program.make(onUpdate); | |
$ce.onchange = (e) => { | |
let ce = e.currentTarget.value; | |
program = Program.updateCelsius(program, ce); | |
}; | |
$fa.onchange = (e) => { | |
let fa = e.currentTarget.value; | |
program = Program.updateFahrenheit(program, fa); | |
}; | |
</script> |
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
type state = { | |
celsius: float, | |
fahrenheit: float, | |
} | |
type action = | |
| UpdateCelsius(float) | |
| UpdateFahrenheit(float) | |
// F = C * (9/5) + 32 | |
let ce2fa = ce => ce *. (9. /. 5.) +. 32. | |
// C = (F - 32) * (5/9) | |
let fa2ce = fa => (fa -. 32.) *. (5. /. 9.) | |
let reduce = (state, action) => { | |
switch (state, action) { | |
| (_, UpdateCelsius(celsius)) => { | |
celsius, | |
fahrenheit: celsius->ce2fa, | |
} | |
| (_, UpdateFahrenheit(fahrenheit)) => { | |
fahrenheit, | |
celsius: fahrenheit->fa2ce, | |
} | |
} | |
} | |
let initialState = { | |
celsius: 5., | |
fahrenheit: ce2fa(5.), | |
} | |
module Program = { | |
type t = { | |
state: state, | |
onUpdate: (state, state) => unit, | |
} | |
let make = onUpdate => { | |
state: initialState, | |
onUpdate, | |
} | |
let dispatch = (program, action) => { | |
let prev = program.state | |
let next = program.state->reduce(action) | |
program.onUpdate(prev, next) | |
next | |
} | |
let updateCelsius = (program, ce) => { | |
let state = program->dispatch(UpdateCelsius(ce)) | |
{...program, state} | |
} | |
let updateFahrenheit = (program, fa) => { | |
let state = program->dispatch(UpdateFahrenheit(fa)) | |
{...program, state} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment