Skip to content

Instantly share code, notes, and snippets.

@petermoresi
Created January 11, 2018 08:28
Show Gist options
  • Save petermoresi/eb8178b3c4cd0712f008c7e95a073923 to your computer and use it in GitHub Desktop.
Save petermoresi/eb8178b3c4cd0712f008c7e95a073923 to your computer and use it in GitHub Desktop.
import React from "react";
import { dispatch, createStore } from "xander";
import Formula, { branch, filter, compile, isText, isArray } from "formula";
import colors from "./colors";
// Create a store to manage the value for key "name".
createStore("name", (state = "", { type, data }) =>
branch(type == "SetName", data, state)
);
let queryStore = createStore(
"query",
(state = 'search("pink", name) > 0', { type, data }) =>
branch(type == "SetQuery", data, state)
);
let dataStore = createStore("data", (state = [], { type, data }) =>
branch(type == "SetData", data, state)
);
createStore("output", (state = {}, { type, data }, waitFor) => {
return branch(
type == "SetQuery" || type === "SetData",
() => {
waitFor([queryStore.dispatchToken, dataStore.dispatchToken]);
console.log("update output");
let query = queryStore.getState();
let data = dataStore.getState();
let ms = 0;
try {
var start = new Date();
data = filter(data, query);
ms = new Date() - start;
} catch (e) {
data = e.toString();
}
return { ms, data };
},
state
);
});
dispatch("SetData", colors);
export default ({ query, data, output }) => {
output = output.data || [];
let ms = output.ms || 0;
let ast = output.ast || [];
return (
<div>
<h1>Color Search</h1>
<div>
<textarea
cols="100"
rows="4"
onChange={event => dispatch("SetQuery", event.target.value)}
value={query}
/>
</div>
{/* <pre>{JSON.stringify(output || "", null, 4)}</pre> */}
Found: {output.length} out of {colors.length} in {ms}ms
{branch(isText(output), <div>{output}</div>, isArray(output), () => (
<table style={{ margin: 10 }} width="80%" border="1">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>hex</th>
</tr>
</thead>
<tbody>
{(output || []).map((d, i) => (
<tr key={i}>
<td>{d.id}</td>
<td>{d.name}</td>
<td
style={{
color:
parseInt(d.hex.substr(1), 16) <= parseInt("6E5160", 16)
? "white"
: "black",
backgroundColor: d.hex,
width: 100,
height: 30
}}
>
{d.hex}
</td>
</tr>
))}
</tbody>
</table>
))}
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment