Skip to content

Commit

Permalink
feat(lastIndexOf): add NaN handling logic
Browse files Browse the repository at this point in the history
  • Loading branch information
evan-moon committed Dec 1, 2024
1 parent 53d96a9 commit cf0bb03
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/compat/array/lastIndexOf.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ describe('lastIndexOf', () => {
expect(lastIndexOf(array, 3)).toBe(5);
});

it(`should work with \`NaN\``, () => {
expect(lastIndexOf([1, 2, 3, NaN, 1, 2], NaN)).toBe(3);
});

it(`should work with a positive \`fromIndex\``, () => {
expect(lastIndexOf(array, 1, 2)).toBe(0);
});
Expand Down
26 changes: 26 additions & 0 deletions src/compat/array/lastIndexOf.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import { isArrayLike } from '../predicate/isArrayLike';

/**
* Finds the index of the last occurrence of a value in an array.
*
* This method is similar to `Array.prototype.lastIndexOf`, but it also finds `NaN` values.
* It uses strict equality (`===`) to compare elements.
*
* @template T - The type of elements in the array.
* @param {ArrayLike<T> | null | undefined} array - The array to search.
* @param {T} searchElement - The value to search for.
* @param {number} [fromIndex] - The index to start the search at.
* @returns {number} The index (zero-based) of the last occurrence of the value in the array, or `-1` if the value is not found.
*
* @example
* const array = [1, 2, 3, NaN, 1];
* lastIndexOf(array, 3); // => 4
* lastIndexOf(array, NaN); // => 3
*/
export function lastIndexOf<T>(array: ArrayLike<T> | null | undefined, searchElement: T, fromIndex?: number): number {
if (!isArrayLike(array) || array.length === 0) {
return -1;
Expand All @@ -12,5 +29,14 @@ export function lastIndexOf<T>(array: ArrayLike<T> | null | undefined, searchEle
index = index < 0 ? Math.max(length + index, 0) : Math.min(index, length - 1);
}

// `Array.prototype.lastIndexOf` doesn't find `NaN` values, so we need to handle that case separately.
if (Number.isNaN(searchElement)) {
for (let i = index; i >= 0; i--) {
if (Number.isNaN(array[i])) {
return i;
}
}
}

return Array.from(array).lastIndexOf(searchElement, index);
}

0 comments on commit cf0bb03

Please sign in to comment.