Today I Learned - Rocky Kev

TIL mutations and how to sort without mutating

POSTED ON:

TAGS:

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:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.