Skip to content

Instantly share code, notes, and snippets.

@leetrout
Created February 12, 2012 01:04
Show Gist options
  • Save leetrout/1805535 to your computer and use it in GitHub Desktop.
Save leetrout/1805535 to your computer and use it in GitHub Desktop.
JavaScript Array Insert and Bisect
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