Issue #68. Adding _.sortedIndexOf

This commit is contained in:
Jeremy Ashkenas
2010-12-17 10:35:53 -05:00
parent 3a113d2d88
commit 8c2570b0ba
3 changed files with 39 additions and 1 deletions

View File

@@ -254,6 +254,8 @@
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
// Unlike `_.sortedIndexOf`, this function returns the array at which an
// element *should* be inserted, not where it actually is.
_.sortedIndex = function(array, obj, iterator) {
iterator = iterator || _.identity;
var low = 0, high = array.length;
@@ -264,6 +266,14 @@
return low;
};
// Similar to native `indexOf`, but assumes that the array being searched
// is already sorted, giving much faster performance on large arrays.
// Not to be confused with `_.sortedIndex`.
_.sortedIndexOf = function(array, obj) {
var i = _.sortedIndex(array, obj);
return array[i] === obj ? i : -1;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];