Skip to content

Instantly share code, notes, and snippets.

@Yord
Last active September 30, 2016 06:54
Show Gist options
  • Save Yord/92a78f74ca62e4b02911bee42c1ff278 to your computer and use it in GitHub Desktop.
Save Yord/92a78f74ca62e4b02911bee42c1ff278 to your computer and use it in GitHub Desktop.
// If you haven't already, watch Brian Lonsdorf's "Hey Underscore, You're Doing It Wrong!":
// http://functionaltalks.org/2013/05/27/brian-lonsdorf-hey-underscore-youre-doing-it-wrong/
const { append, eqProps, identity, map, mergeWith, nthArg, pipe, reject, when } = require('Ramda');
const idEquals = eqProps('id');
// Reducers as data-less action function (returns a function that
// takes a state and returns a new state without mutation)
const todo = action => {
switch(action.type) {
case 'TODO_UPDATE': {
return mergeWith(nthArg(0), action.params);
}
default: {
return identity;
}
}
};
const todos = action => {
switch(action.type) {
case 'TODO_ADD': {
return append({ id: action.id, text: action.params.text, completed: true });
}
case 'TODO_UPDATE': {
return map(
when(idEquals(action))(
todo(action)
)
);
}
case 'TODO_DELETE': {
return reject(idEquals(action));
}
default: {
return identity;
}
}
};
// Concrete Actions
const addTodo1 = todos({ type: 'TODO_ADD', id: 1, params: { text: 'Foo' } });
const updateTodo1 = todos({ type: 'TODO_UPDATE', id: 1, params: { text: 'Bar', completed: false } });
const deleteTodo0 = todos({ type: 'TODO_DELETE', id: 0 });
// Action plan
const changes = pipe(
addTodo1,
updateTodo1,
deleteTodo0
);
// State changes
const stateBefore = [{ id: 0, text: 'Foo', completed: true }];
const stateAfter = changes(stateBefore);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment