Skip to content

Instantly share code, notes, and snippets.

@fredyr
Created March 19, 2017 19:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredyr/0a6dd666e18c7de30e64ea6cb0880c5c to your computer and use it in GitHub Desktop.
Save fredyr/0a6dd666e18c7de30e64ea6cb0880c5c to your computer and use it in GitHub Desktop.
Binary clock using Reason/React
type bitnum = (int, list bool);
let elem_of_list ls => ReactRe.arrayToElement (Array.of_list ls);
let text s => ReactRe.stringToElement s;
let cell_col bit => {
let color = if bit {"light"} else {"dark"};
<div className=("cell " ^ color) />
};
let cell_val digit => <div className="cell"> (text @@ string_of_int digit) </div>;
let column (digit, bits) => {
let cells = List.map cell_col bits @ [cell_val digit];
<div className="col"> (elem_of_list cells) </div>
};
let columns cs => {
let cols = List.map column cs;
<div className="colpair"> (elem_of_list cols) </div>
};
let legend digits => {
let cells = List.map cell_val digits;
<div className="col legend"> (elem_of_list cells) </div>
};
let bitnum_of_int (n: int) :bitnum => {
let masks = List.map2 (land) [8, 4, 2, 1] [n, n, n, n];
let bits = List.map (fun x => x > 0) masks;
(n, bits)
};
let decimal_parts (n: int) :list int => [n / 10, n mod 10];
module BinaryClock = {
include ReactRe.Component.Stateful;
type props = unit;
type state = {time: Js.Date.t};
let name = "BinaryClock";
let time_now () => {time: Js.Date.fromFloat (Js.Date.now ())};
let getInitialState _ => time_now ();
let componentDidMount {setState} => {
let onUpdate () => {
let stateSetter {state} => time_now ();
setState stateSetter
};
let _ = ReasonJs.setInterval (fun () => onUpdate ()) 1000;
None
};
let render {state} => {
let conv x => int_of_float x |> decimal_parts |> List.map bitnum_of_int;
let cols =
[Js.Date.getHours state.time, Js.Date.getMinutes state.time, Js.Date.getSeconds state.time] |>
List.map conv |>
List.map columns;
<div> (elem_of_list ([legend [8, 4, 2, 1]] @ cols)) </div>
};
};
include ReactRe.CreateComponent BinaryClock;
let createElement = wrapProps ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment