Skip to content

Instantly share code, notes, and snippets.

@mofas
Last active October 19, 2016 03:51
Show Gist options
  • Save mofas/3c8ed8af46e896942d18fc859c28b8ed to your computer and use it in GitHub Desktop.
Save mofas/3c8ed8af46e896942d18fc859c28b8ed to your computer and use it in GitHub Desktop.
//immutable_fractal_updater
state = [
{
key: 'key1'
value: true,
children: [
{
key: 'key4'
value: true,
children: [
...
]
},
...
]
},
...
]
const fractalUpdater = predicate => field => updater => state => {
return state.map(d=>{
if(predicate(d)){
return d.updateIn(field, updater);
}
return d;
});
}
const keyPredicate = key => data => {
return data.get('key') === key;
}
//update key:key1, value <- false
fractalUpdater(keyPredicate('key1'))(['value'])(false)(state);
//update key:key4, value <- false
fractalUpdater(keyPredicate('key1'))(['children'])(fractalUpdater(keyPredicate('key4'))(['value'])(false))(state);
//update key:key4, push children Map({key: key9, value: true, children:null})
fractalUpdater(keyPredicate('key1'))(['children'])(
fractalUpdater(keyPredicate('key4'))(['children'])((v)=>v.push(Map({key: 'key9', value: true, children:null})))
)(state);
//update key:key1, value <- false, key:key4, value <- false
compose(
fractalUpdater(keyPredicate('key1'))(['value'])(false),
fractalUpdater(keyPredicate('key1'))(['children'])(fractalUpdater(keyPredicate('key4'))(['value'])(false))(state)
)
//fractal component
const fractalComponent = (updater) => (data) => {
const key = data.get('key');
const value = data.get('value');
return (
<div
onClick={()=>updater(keyPredicate(key))(['value'])(!value)(data)}
>
Value: {value}
{
data.get('children').map(fractalComponent(updater(keyPredicate(key))(['children'])))
}
</div>
);
}
//init
fractalComponent(fractalUpdater)(state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment