Last active
July 8, 2021 09:54
-
-
Save fvilante/b83deaf4a868febdc0d4cdfb5b1c5ae9 to your computer and use it in GitHub Desktop.
Meiosis pattern in typescript (a simple example)
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
// uses 'flyd' stream micro-library | |
type Stream = (_: number) => Stream // this life is a simplification | |
interface Model { | |
value: number | |
} | |
interface Actions { | |
increment: () => void | |
decrement: () => void | |
} | |
interface App { | |
Initial: () => Model | |
Actions: (_: Stream) => Actions | |
} | |
// ============== | |
const app: App = { | |
Initial = () => { value: 0 } | |
Actions = _stream => { | |
increment: () => _stream(1), | |
decrement: () => _stream(-1), | |
} | |
} | |
const update = flyd.stream() // #1 - update stream | |
const states = flyd.scan( // #3 - scan update stream with initial value | |
(state, increment) => // and apply patchs to the state with an reducer funcion | |
state.value = state.value + increment | |
, app.Initial(), update) | |
const actions = app.Actions(update) // #2 - Push actions on stream | |
states.map( state => // # 4 - map to display stream | |
document.write("<pre>" + JSON.stringify(state) + "</pre>") | |
//run | |
actions.increment() | |
actions.increment() | |
actions.decrement() |
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
// More generic version | |
// Using Function Patches | |
interface State { | |
temperature: { | |
value: number | |
units: 'C' | |
} | |
} | |
const initialState: State { | |
temperature: { | |
value: 22, | |
units: 'C' | |
} | |
} | |
//action | |
const increment = amount => update( state => state.temperature.value += amount ) | |
//reducer | |
const update = flyd.stream() | |
const states = flyd.scan( (state, patch) => patch(state), initialState, update ) | |
// | |
const actions = temperature.Actions(update) | |
state.map( state => document.write( | |
'<pre> + JSON.stringfy(state, null, 2) + '</pre>' | |
)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment