Created
February 13, 2014 16:11
-
-
Save Rycochet/8978011 to your computer and use it in GitHub Desktop.
Grow (or shrink) an array - alters the 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
/** | |
* Grow (or shrink) an array - alters the array | |
* @param {number} length | |
* @param {?*...} add these entries and repeat | |
* @returns this | |
*/ | |
Array.prototype.grow = function(length, add) { | |
var i = 0, len = this.length, args = Array.prototype.slice.call(arguments, 1); | |
if (this.length < length) { | |
args = args.length ? args : [0]; | |
while (this.length < length) { | |
if (i >= args.length) { | |
i = 0; | |
} | |
this.push(args[i++]); | |
} | |
} else { | |
while (this.length > length) { | |
this.pop(); | |
} | |
} | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment