Last active
September 10, 2017 18:02
-
-
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.
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
//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