Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Non-destructive sort and reverse (See related posts)

Array.prototype.clone = function(){
	return Array.apply(null,this)
};
Array.prototype.sortIt    = Array.prototype.sort;
Array.prototype.reverseIt = Array.prototype.reverse;
Array.prototype.sort = function(){
	var tmp = this.clone();
	return tmp.sortIt.apply(tmp,arguments)
}
Array.prototype.reverse = function(){
	var tmp = this.clone();
	return tmp.reverseIt.apply(tmp,arguments)
}

* before

var a = [5,4,3,2,1];
var b = a.sort();
alert(a); // [1,2,3,4,5]
alert(b); // [1,2,3,4,5]

var a = [1,2,3,4,5];
var b = a.reverse();
alert(a); // [5,4,3,2,1]
alert(b); // [5,4,3,2,1]


* after

var a = [5,4,3,2,1];
var b = a.sort();
alert(a); // [5,4,3,2,1]
alert(b); // [1,2,3,4,5]
a.sortIt();
alert(a); // [1,2,3,4,5]

var a = [1,2,3,4,5];
var b = a.reverse();
alert(a); // [1,2,3,4,5]
alert(b); // [5,4,3,2,1]
a.reverseIt();
alert(a); // [5,4,3,2,1]

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts