andy-h
2/5/2014 - 3:54 PM

Array.prototype.prune() is the opposite of Array.prototype.slice(). It removes the specified portion of the array and returns what's left, w

Array.prototype.prune() is the opposite of Array.prototype.slice(). It removes the specified portion of the array and returns what's left, without modifying the original array.

//returns a copy of an array with a portion removed
//(essentially the opposite of `slice`)
//the `end` argument is optional

//arr.prune(begin[, end])

if(!Array.prototype.prune){
	Array.prototype.prune = function prune(begin, end){
		"use strict";
		var newArr = this.slice(0);	//make a copy of the array
		
		//make `begin` a positive index
		if(!begin) begin = 0;
		else if(begin < 0) begin = Math.max(0, this.length+begin);
		
		//try to make `end` a positive index
		if(end === void 0) end = this.length;
		else if(!end) end = 0;
		else if(end < 0) end = this.length+end;
		
		if(end <= begin) return newArr;	//don't remove anything; return full array
		
		newArr.splice(begin, end-begin);	//remove specified elements
		return newArr;
	};
}