extender – Array [ 707 views ]
Goal: give some additional function to the Array type
// 1. remove the specified element
TypeExtend(Array, 'remove', function(from, to) {
try{
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
}
catch(e){
return false;
}
});
// 2. remove all listed elements (passed as arguments)
TypeExtend(Array, 'removeA', function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
});
// 3. shuffle the items
TypeExtend(Array, 'shuffle', function() {
var i = this.length, j, temp;
while ( --i )
{
j = Math.floor( Math.random() * (i - 1) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
return this;
});
// 4. return a new array with distincted items
TypeExtend(Array, 'distinct', function() {
var map = {}, out = [];
for(var i=0, l=this.length; i