Last active
August 29, 2015 14:28
-
-
Save real34/da760763127b54dd6f6b to your computer and use it in GitHub Desktop.
Simple CycleJS cells sum
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
/** @jsx hJSX */ | |
import {run, Rx} from '@cycle/core'; | |
import {makeDOMDriver, hJSX} from '@cycle/dom'; | |
const initialGrid = [ | |
[1, 5, 6], | |
[2, 15, 0], | |
[21, 1, 0], | |
[22, 1, 42], | |
]; | |
function cellStyle(x, y, activeCells) { | |
let isActive = activeCells.has(`${x}-${y}`); | |
return { | |
background: isActive ? 'green' : 'red', | |
border:"1px solid red", | |
height: "4rem", | |
width: "4rem", | |
"text-align": "center" | |
}; | |
} | |
function intent(DOM) { | |
return { | |
toggleCell$: DOM.get('.cell', 'mouseenter') | |
.map(e => e.target.id.split('-')) | |
.map(([cell, x, y]) => `${x}-${y}`) | |
} | |
} | |
function model(actions) { | |
return { | |
grid$: Rx.Observable.just(initialGrid), | |
activeCells$: actions.toggleCell$.scan((active, cellCoords) => { | |
active.has(cellCoords) ? active.delete(cellCoords) : active.add(cellCoords); | |
return active; | |
}, new Set()).startWith(new Set()), | |
} | |
} | |
function view({grid$, activeCells$}) { | |
const content$ = Rx.Observable.combineLatest(grid$, activeCells$, (grid, activeCells) => { | |
const cellsTable$ = <table> | |
{grid.map((row, x) => <tr> | |
{row.map((cell, y) => <td className="cell" style={cellStyle(x, y, activeCells)} id={"cell-" + x + "-" + y}>{cell}</td>)} | |
</tr>)} | |
</table>; | |
const sum$ = Rx.Observable.from(activeCells.values()) | |
.map(coords => coords.split('-')) | |
.map(([x, y]) => grid[x][y]) | |
.sum() | |
.map(sum => <span>{sum}</span>); | |
return <div> | |
{cellsTable$} | |
<p> | |
<strong>Sum = </strong> {sum$} | |
</p> | |
</div> | |
}); | |
return Rx.Observable.just(<div> | |
<h1>Super sum machine!</h1> | |
{content$} | |
</div>); | |
} | |
function main({DOM}) { | |
const vtree$ = view(model(intent(DOM))); | |
return { | |
DOM: vtree$ | |
} | |
} | |
run(main, { | |
DOM: makeDOMDriver('#sum-app') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment