Created
September 26, 2017 01:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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