From a655a7a1a1fe34107d80df774548a5c9fce0334c Mon Sep 17 00:00:00 2001 From: smaillz Date: Thu, 15 Jun 2023 16:26:30 +0300 Subject: [PATCH] add findLastIndex for array --- src/array/__tests__/findLastIndex.ts | 22 ++++++++++++++++++++ src/array/findLastIndex.ts | 31 ++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 src/array/__tests__/findLastIndex.ts create mode 100644 src/array/findLastIndex.ts diff --git a/src/array/__tests__/findLastIndex.ts b/src/array/__tests__/findLastIndex.ts new file mode 100644 index 0000000..22ddd68 --- /dev/null +++ b/src/array/__tests__/findLastIndex.ts @@ -0,0 +1,22 @@ +import findLastIndex from '../findLastIndex'; + +describe('utils/array/findLastIndex', () => { + it('should return founded value or undefined otherwise', () => { + const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1]; + + expect(findLastIndex((a) => a > 3, arr)).toBe(5); + expect(findLastIndex((a) => a > 100, arr)).toBe(-1); + expect(findLastIndex((a) => a % 2 === 0)(arr)).toBe(7); + }); + + it('test callback parameters', () => { + const fn = jest.fn(); + const arr = [1, 2, 3]; + + findLastIndex(fn, arr); + + expect(fn).toHaveBeenCalledWith(3, 2, arr); + expect(fn).toHaveBeenCalledWith(2, 1, arr); + expect(fn).toHaveBeenCalledWith(1, 0, arr); + }); +}); diff --git a/src/array/findLastIndex.ts b/src/array/findLastIndex.ts new file mode 100644 index 0000000..56b9257 --- /dev/null +++ b/src/array/findLastIndex.ts @@ -0,0 +1,31 @@ +import curryN from '../function/curryN'; +import { ArrPred } from '../typings/types'; + +interface FindLastIndex { + (fn: ArrPred, list: ArrayLike): number; + (fn: ArrPred): (list: ArrayLike) => number; +} + +/** + * Returns the index of the last element of the list which matches the + * predicate, or `-1` if no element matches. + * + * @param {Function} fn The predicate function used to determine if the element is the + * desired one. + * @param {Array} arr The array to consider. + * @return {Number} The index of the element found, or `-1`. + * @example + * + * var xs = [{a: 1}, {a: 2}, {a: 3}, {a: 2}, {a: 1}]; + * findLastIndex(x => x.a === 2)(xs); //=> 3 + * findLastIndex(x => x.a === 4)(xs); //=> -1 + */ +export default curryN(2, (fn: ArrPred, arr: ArrayLike = []) => { + for (let i = arr.length - 1; i >= 0; i--) { + if (fn(arr[i], i, arr)) { + return i; + } + } + + return -1; +}) as FindLastIndex;