Skip to content

Instantly share code, notes, and snippets.

@cameronbourke
Last active October 30, 2016 08:29
Show Gist options
  • Save cameronbourke/30768541323caeaa5dad to your computer and use it in GitHub Desktop.
Save cameronbourke/30768541323caeaa5dad to your computer and use it in GitHub Desktop.
After watching Dan Abramov's egghead series on Redux, https://egghead.io/lessons/javascript-redux-the-single-immutable-state-tree, I quickly played around with how native array methods in javascript could be immutable. This is focused on the methods not like map, reduce, filter etc which already don't mutate the array.
const pop = (array) => array.splice(0, -1);
const push = (array, el) => [...array, el];
const splice = (array = [], startCount, deleteCount = 0, ...elements) => {
const { length } = array;
let remainder = startCount + deleteCount;
if(startCount > length || startCount <= -length) {
startCount = 0;
} else if(startCount < 0) {
startCount = length + startCount;
const elementsRemain = length - startCount <= deleteCount;
remainder = elementsRemain ? length : startCount + deleteCount;
}
if(deleteCount < 0) deleteCount = 0;
return [
...array.slice(0, startCount),
...elements,
...array.slice(remainder)
];
};
const shift = (array) => array.slice(1);
const reverse = (array) => {
return [...array].reverse();
};
export default const iam {
pop,
push,
splice,
shift,
reverse
};
@albertstartup
Copy link

nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment