Last active
December 20, 2015 04:19
-
-
Save KrystianP/6070093 to your computer and use it in GitHub Desktop.
Extend Prototype Array
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
if(!Array.prototype.inArray){ | |
Array.prototype.inArray = function (elem){ | |
for(i=0, j = this.length; i < j; i++){ | |
if(this[i] == elem) return true; | |
} | |
return false; | |
} // end Array.prototype.inArray | |
} | |
// example | |
// >>> var x = [1,2,3,4]; | |
// >>> x.inArray(4); | |
// true | |
// ====================================================== | |
if(!Array.prototype.randomItem){ | |
Array.prototype.randomItem = function(){ | |
return this[Math.floor(Math.random() * this.length)]; | |
} | |
} | |
// example | |
// >>> items = [1,2,3,4,5,6,7,8,9]; | |
// >>> items.randomItem(); | |
// 5 | |
//====================================================== | |
// This function shuffles (randomizes the order of the elements in) an array. | |
if(!Array.prototype.shuffles){ | |
Array.prototype.shuffles = function(){ | |
for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); | |
} | |
} | |
// example | |
// >>> items = [1,2,3,4,5,6,7,8,9]; | |
// >>> items.shuffles(); | |
// >>> items | |
// [9,8,5,6,3,4,7,2,1] | |
//====================================================== | |
if(! Array.prototype.diff){ | |
Array.prototype.diff = function(c, m){ | |
var d = [], e = -1, h, i, j, k; | |
for(i = c.length, k = this.length; i--;){ | |
for(j = k; j && (h = c[i] !== this[--j]);); | |
h && (d[++e] = m ? i : c[i]); | |
} | |
return d; | |
} | |
} | |
// example | |
// >>> var x = [1,2,3,67]; | |
// >>> x.diff( [1,2,6,5]); | |
// >>> [6,5] | |
//====================================================== | |
if(!Array.prototype.removeDuplicated){ | |
Array.prototype.removeDuplicated = function(s){ | |
var p, i, j; | |
for(i = this.length; i;){ | |
for(p = --i; p > 0;) | |
if(this[i] === this[--p]){ | |
for(j = p; p-- && this[i] === this[p];); | |
i -= this.splice(p + 1, j - p).length; | |
} | |
} | |
if(s){ | |
flag = true; | |
for(var i = 0, j = this.length; i < j; i++){ | |
if(isNaN(parseFloat(this[i]))){flag = false; break;} | |
} | |
if(!flag) this.sort(); | |
else this.sort(function(a,b){return a-b}); | |
} | |
return this; | |
} | |
} | |
// example | |
// >>> var x = [10,1,1,1,8,8,8,9,10,8,1,2,3,67]; | |
// >>> x.removeDuplicated(); | |
// >>> [9, 10, 8, 1, 2, 3, 67] | |
// >>> x.removeDuplicated(true); sort = true | |
// [1, 2, 3, 8, 9, 10, 67] | |
// >>> var x = [10,1,1,1,8,8,8,9,10,8,1,2,3,67, 'test']; | |
// >>> x.removeDuplicated(); | |
// [1, 10, 2, 3, 67, 8, 9, "test"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment