Skip to content

Instantly share code, notes, and snippets.

@wizard04wsu
Last active September 10, 2017 18:02
Show Gist options
  • Save wizard04wsu/8826678 to your computer and use it in GitHub Desktop.
Save wizard04wsu/8826678 to your computer and use it in GitHub Desktop.
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;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment