Add strictIndexOf and strictLastIndexOf helpers.

This commit is contained in:
John-David Dalton
2016-08-17 11:40:11 -07:00
parent f9936b8b54
commit 1bf125eebd

View File

@@ -817,18 +817,9 @@
* @returns {number} Returns the index of the matched value, else `-1`. * @returns {number} Returns the index of the matched value, else `-1`.
*/ */
function baseIndexOf(array, value, fromIndex) { function baseIndexOf(array, value, fromIndex) {
if (value !== value) { return value === value
return baseFindIndex(array, baseIsNaN, fromIndex); ? strictIndexOf(array, value, fromIndex)
} : baseFindIndex(array, baseIsNaN, fromIndex);
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
} }
/** /**
@@ -1268,6 +1259,48 @@
return result; return result;
} }
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* A specialized version of `_.lastIndexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictLastIndexOf(array, value, fromIndex) {
var index = fromIndex + 1;
while (index--) {
if (array[index] === value) {
return index;
}
}
return index;
}
/** /**
* Gets the number of symbols in `string`. * Gets the number of symbols in `string`.
* *
@@ -7262,21 +7295,11 @@
var index = length; var index = length;
if (fromIndex !== undefined) { if (fromIndex !== undefined) {
index = toInteger(fromIndex); index = toInteger(fromIndex);
index = ( index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
index < 0
? nativeMax(length + index, 0)
: nativeMin(index, length - 1)
) + 1;
} }
if (value !== value) { return value === value
return baseFindIndex(array, baseIsNaN, index - 1, true); ? strictLastIndexOf(array, value, index)
} : baseFindIndex(array, baseIsNaN, index, true);
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
} }
/** /**