Created
March 18, 2016 16:21
-
-
Save 6ewis/6e3a9604c257ba60b7f3 to your computer and use it in GitHub Desktop.
Teach ramda
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
const state = [ | |
{id: 12, foo: 'bar', 'attribute': 101}, | |
{id: 34, foo: 'baz', 'attribute': 102}, | |
{id: 56, foo: 'qux', 'attribute': 103} | |
]; | |
const action = {payload: {id: 34, attribute: 'attribute'}}; | |
// findObjectIndex :: [Object] -> Int | |
const findObjectIndex = findIndex(propEq('id', action.payload.id)); | |
// removeAttribute :: Object -> ObjectNoAttribute | |
const removeAttribute = dissocPath(['payload', 'attribute']); | |
const index = findObjectIndex(state); | |
const updated = adjust(removeAttribute, index, state); | |
console.log(updated); | |
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
const state = [ | |
{id: 12, foo: 'bar', 'attribute': 101}, | |
{id: 34, foo: 'baz', 'attribute': 102}, | |
{id: 56, foo: 'qux', 'attribute': 103} | |
]; | |
const action = {payload: {id: 34, attribute: 'attribute'}}; | |
//returns a new array - and remove the attribute of the matching id | |
let newObject = state.slice(0); | |
let result = newObject.map((i) => { | |
if (i.id === action.payload.id) { | |
delete i[action.payload.attribute] | |
} | |
return i; | |
}); //return newOject | |
//Takes an object, and checks if object.id is equal to | |
//action.payload.id | |
const isPayload = R.propEq('id', action.payload.id) | |
//When isPayload returns true, it returns a copy | |
//of the object with the specified field removed. | |
//Otherwise it returns the object unaltered | |
const removePayloadAttr = R.when( | |
isPayload, | |
R.dissoc(action.payload.attribute) | |
) | |
let result2 = R.map(removePayloadAttr, state) | |
//Sanity check to ensure the code is doing the same as the original | |
R.equals(result, result2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment