Last active
December 3, 2018 16:54
-
-
Save yukeehan/5fedb138750a92a99b79f9c5f5df5715 to your computer and use it in GitHub Desktop.
changing array and obj without modify original one
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
// remove index-1 position component of array without modify the origin array | |
list = [1, 2, 3, 4, 5] | |
const removeCounter = (list, index) => { | |
return [ | |
...list.slice(0, index), | |
...list.slice(index + 1) | |
]; | |
} | |
removerCounter(list, 3); //[1, 2, 4, 5]; | |
//================================================================== | |
//===== add an counter in an array============= | |
const addCounter = (list) => { | |
return list.concat([0]); | |
}; | |
//===== ES6 ========================= | |
const addCounter = (list) => { | |
return [...list, 0]; | |
}; | |
//========================== Modify Object ES6 way ====================== | |
const toggleTodo = (todo) => { | |
return Object.assign({}, todo, { | |
completed: !todo.completed | |
}); | |
}; | |
// ============================= ES7 way =================================== | |
const toggleTodo = (todo) => { | |
return { | |
...todo, | |
completed: !todo.completed | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://egghead.io/lessons/react-redux-avoiding-object-mutations-with-object-assign-and-spread