Created
February 12, 2012 01:04
-
-
Save leetrout/1805535 to your computer and use it in GitHub Desktop.
JavaScript Array Insert and Bisect
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
Array.prototype.bisect = function (val) { | |
var idx; | |
if (this.length === 0) { | |
return 0; | |
} | |
for (idx=0; idx < this.length; idx++) { | |
if (val < this[idx]) { | |
return idx; | |
} | |
} | |
return idx; | |
}; | |
Array.prototype.insert = function (val, inPlace) { | |
var idx = this.bisect(val); | |
if (inPlace) { | |
this.splice(idx, 0, val); | |
return this; | |
} | |
return this.slice(0, idx).concat([val], this.slice(idx)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment