Rework of #68, to use a flag to indexOf, instead of a separate function.

This commit is contained in:
Jeremy Ashkenas
2010-12-17 10:57:12 -05:00
parent 8c2570b0ba
commit d2d6cfe667
4 changed files with 23 additions and 41 deletions

View File

@@ -254,8 +254,6 @@
// 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;
@@ -266,14 +264,6 @@
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 [];
@@ -366,8 +356,14 @@
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
_.indexOf = function(array, item) {
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
if (isSorted) {
var i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (var i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
return -1;