TIL mutations and how to sort without mutating
POSTED ON:
TAGS: javascript functional-programming arrays
Mutating #
There's times when you want to have your objects mutate.
For example:
const knight = {
name: 'Brienne of Tarth',
height: '1.91m',
allegiance: 'House Tarth'
};
knight.allegiance = 'House Stark';
When it becomes problematic? sort()
will change the array's order.
let listOfArmorTypes = ['helm', 'shoulder', 'body', 'gauntlet', 'torso', 'shoes'];
listOfArmorTypes.sort(); // WILL MUTATE THE ARRAY
listOfArmorTypes[0]; // assumed to be helm, but it's not!
// The new order is:
// ['body', 'gauntlet', 'helm', 'shoes', 'shoulder', 'torso']
Things that mutate:
- pop() & push()
- unshift() & shift()
- sort() & reverse()
- splice()
- copyWithin()
- fill()
NOTE: Mutation isn't bad. It CAN cause side effects and ruin your life.
In the knight example, it's useful when you're fully aware of your mutation.
Avoiding mutations #
let listOfArmorTypes = ['helm', 'shoulder', 'body', 'gauntlet', 'torso', 'shoes'];
const sortedListOfArmorTypes = [...listOfArmorTypes].sort();
console.log(listOfArmorTypes);
// ["helm", "shoulder", "body", "gauntlet", "torso", "shoes"]
console.log(sortedListOfArmorTypes);
// ["body", "gauntlet", "helm", "shoes", "shoulder", "torso"]
Now you have the original, and the changes.
// If you wanted to modify it as well
const listOfGoldenArmorTypes = listOfArmorTypes.map(armorTypes => `golden ${armorTypes}`);
console.log(listOfGoldenArmorTypes);
// ["golden helm", "golden shoulder", "golden body", "golden gauntlet", "golden torso", "golden shoes"]
REFERENCES:
https://blog.sapegin.me/all/avoid-mutation/
https://alistapart.com/article/why-mutation-can-be-scary/
Related TILs
Tagged: javascript