clean-code-javascript
clean-code-javascript copied to clipboard
"Don't write to global functions" section improvement
Two things from my side:
- Is there a reason to use
Setinside the example function? Considering there's alsoArray.prototype.includes:
Array.prototype.diff = function diff(comparisonArray) {
- const hash = new Set(comparisonArray);
- return this.filter(elem => !hash.has(elem));
+ return this.filter(elem => !comparisonArray.includes(elem));
};
- Wouldn't it be better to teach using simple functions instead of whole classes? Who would ever inherit from built-in types and write
const arr = new SuperArray(1, 2, 3)in real life? I think it's more common to have:
function diff(first, second) {
return first.filter(elem => !second.includes(elem));
}
What do you think?
We could change this whole subsection and use a better example. Thanks for bringing this up! If you have an idea that doesn't involve Array and Set diffing and is something else altogether I'm down to accept a PR!
Sorry, I don't really know a better example at the moment. Usually when you mention not to pollute / mutate global scope, you introduce the idea of modules.
Maybe something simple like:
Bad:
Array.prototype.last = function() {
return this[this.length-1];
}
[1,2,3].last();
Good:
function getLastElement(array){
return array[array.length-1]
}
getLastElement([1,2,3]);
And, yeah, the idea of modules could be better for this kind of example, instead of using new, you could explain little of Module Pattern.
const arrayUtils = {
last: (array) => array[array.length-1]
}