Skip to content

Instantly share code, notes, and snippets.

@gor181
Last active October 27, 2017 10:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gor181/49c660c14f4d80c89e3f to your computer and use it in GitHub Desktop.
Save gor181/49c660c14f4d80c89e3f to your computer and use it in GitHub Desktop.
Delegation, object mutation and how to avoid it. Javascript.
//Some of the examples use spread syntax available via Babel in ES7 proposal.
//Live at: https://jsbin.com/zawavekepo/edit?js,console
//Arrays, slicing and avoiding mutations
const numArray = [10, 20, 30, 40, 50, 60];
const removeAtIndex = (arr, x) => {
return [
...arr.slice(0, x),
...arr.slice(x + 1)
];
};
const appendAtIndex = (arr, i, what) => {
return [
...arr.slice(0, i),
what,
...arr.slice(i + 1)
];
};
console.log(removeAtIndex(numArray, 2)); // [10, 20, 40, 50, 60]
console.log(appendAtIndex(numArray, 1, 12)); //[10, 12, 30, 40, 50, 60]
//Delegation, prototypal inheritance
const itemProto = { getItem() { return 1; }};
const itemImageProto = { getImage() { return 'http://....' }};
const item = Object.assign({}, itemProto, itemImageProto);
console.log(item.getItem()); // 1
console.log(item.getImage()); // "http://...."
// Do item.getImage and itemImageProto.getImage share the same reference?
console.log(item.getImage === itemImageProto.getImage); //true
// Object mutations
const objectToMutate = { a : { name: 'b' }};
const newObject = Object.assign({}, objectToMutate);
newObject.a.surname = 'Some Value'; // Directly mutated objectToMutate.a
console.log('objectToMutate', objectToMutate); // a: { name: "b", surname: "Some Value" }
console.log('newObject', newObject); // a: { name: "b", surname: "Some Value" }
// And how to avoid it?
const objectToMutate2 = { a : { name: 'b' }};
let newObject2 = Object.assign({}, objectToMutate);
newObject2 = Object.assign({
a: Object.assign({ surname: 'Some Value'}, objectToMutate2.a)
});
console.log('objectToMutate2', objectToMutate2); //a: { name: "b" }
console.log('newObject', newObject2); // a: { name: "b", surname: "Some Value" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment