Last active
March 20, 2017 14:07
-
-
Save gt3/4665ef4866725f4d36558192b0633247 to your computer and use it in GitHub Desktop.
Temperature Calculator with Channels
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 { scaleNames, TemperatureInput, BoilingVerdict } from "./presentation.jsx" | |
import { chan, putAsync } from "js-csp" | |
import { RenderProcess } from "upcoming-react-csp-framework" | |
let NA = Symbol("empty") | |
function sanitize(input) { | |
let parsed = parseFloat(input), invalid = Number.isNaN(parsed) && NA | |
return { input, parsed, invalid } | |
} | |
let format = v => `${v === NA ? "" : Math.round(v * 1000) / 1000}` | |
const intake = { toC: chan(), toF: chan() } | |
let doToC = input => putAsync(intake.toC, sanitize(input)) | |
let doToF = input => putAsync(intake.toF, sanitize(input)) | |
function toC(appState, msg) { | |
let { parsed: p, input: f, invalid } = msg.value | |
let c = format(invalid || (p - 32) * 5 / 9) | |
return { c, f } | |
} | |
function toF(appState, msg) { | |
let { parsed: p, input: c, invalid } = msg.value | |
let f = format(invalid || p * 9 / 5 + 32) | |
return { f, c } | |
} | |
class Calculator extends Component { | |
state = { c: "", f: "" } | |
setAppState = (updater, publisher, [msg]) => this.setState(s => updater(s, msg)) | |
render() { | |
return ( | |
<div> | |
<RenderProcess renderApp={this.setAppState} intake={intake} handlers={{ toC, toF }} /> | |
<TemperatureInput value={this.state.c} onChange={doToF} scale="c" /> | |
<TemperatureInput value={this.state.f} onChange={doToC} scale="f" /> | |
<BoilingVerdict celsius={parseFloat(this.state.c)} /> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment