Skip to content

Instantly share code, notes, and snippets.

@adyngom
Created September 26, 2017 01:26
Show Gist options
  • Save adyngom/30d7772aa20d7f1394edd3714e211389 to your computer and use it in GitHub Desktop.
Save adyngom/30d7772aa20d7f1394edd3714e211389 to your computer and use it in GitHub Desktop.
Javascript few useful array methods to use without accidentally touching the Array.prototype and create a possible conflict
class List extends Array {
constructor() {
super(...arguments);
}
uniq() {
return [... new Set(this)];
}
empty() {
return this.length = 0;
}
flatten() {
return this
.toString()
.split(',')
.reduce( (a,c) => {
let i = parseFloat(c);
c = (!Number.isNaN(i)) ? i : c;
a.push(c);
return a;
}, []);
}
tupl() {
return Object.freeze(this);
}
};
console.log(List.prototype.flatten.call([[1,2,3],4,5,"h","e",["l","l","o"], 3.75]));
// outputs - [1, 2, 3, 4, 5, "h", "e", "l", "l", "o", 3.75]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment