Skip to content

Commit ac64508

Browse files
jaw0r3kkyranetJiralite
authoredNov 5, 2023
feat: support findLast and reduceRight methods (#9573)
* feat(collection): findLast and reverseRight * chore(collection): performance and tests change Co-authored-by: kyra <kyradiscord@gmail.com> * remove unnecessary code * Update packages/collection/src/collection.ts Co-authored-by: Aura Román <kyradiscord@gmail.com> * Apply suggestions from code review Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com> --------- Co-authored-by: kyra <kyradiscord@gmail.com> Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
1 parent c051ed9 commit ac64508

File tree

2 files changed

+159
-0
lines changed

2 files changed

+159
-0
lines changed
 

‎packages/collection/__tests__/collection.test.ts

+70
Original file line numberDiff line numberDiff line change
@@ -908,3 +908,73 @@ describe('random thisArg tests', () => {
908908
}, array);
909909
});
910910
});
911+
912+
describe('findLast() tests', () => {
913+
const coll = createTestCollection();
914+
test('it returns last matched element', () => {
915+
expect(coll.findLast((value) => value % 2 === 1)).toStrictEqual(3);
916+
});
917+
918+
test('throws if fn is not a function', () => {
919+
// @ts-expect-error: Invalid function
920+
expectInvalidFunctionError(() => createCollection().findLast());
921+
// @ts-expect-error: Invalid function
922+
expectInvalidFunctionError(() => createCollection().findLast(123), 123);
923+
});
924+
925+
test('binds the thisArg', () => {
926+
coll.findLast(function findLast() {
927+
expect(this).toBeNull();
928+
return true;
929+
}, null);
930+
});
931+
});
932+
933+
describe('findLastKey() tests', () => {
934+
const coll = createTestCollection();
935+
test('it returns last matched element', () => {
936+
expect(coll.findLastKey((value) => value % 2 === 1)).toStrictEqual('c');
937+
});
938+
939+
test('throws if fn is not a function', () => {
940+
// @ts-expect-error: Invalid function
941+
expectInvalidFunctionError(() => createCollection().findLastKey());
942+
// @ts-expect-error: Invalid function
943+
expectInvalidFunctionError(() => createCollection().findLastKey(123), 123);
944+
});
945+
946+
test('binds the thisArg', () => {
947+
coll.findLastKey(function findLastKey() {
948+
expect(this).toBeNull();
949+
return true;
950+
}, null);
951+
});
952+
});
953+
954+
describe('reduceRight() tests', () => {
955+
const coll = createTestCollection();
956+
957+
test('throws if fn is not a function', () => {
958+
// @ts-expect-error: Invalid function
959+
expectInvalidFunctionError(() => coll.reduceRight());
960+
// @ts-expect-error: Invalid function
961+
expectInvalidFunctionError(() => coll.reduceRight(123), 123);
962+
});
963+
964+
test('reduce collection into a single value with initial value', () => {
965+
const sum = coll.reduceRight((a, x) => a + x, 0);
966+
expect(sum).toStrictEqual(6);
967+
});
968+
969+
test('reduce collection into a single value without initial value', () => {
970+
const sum = coll.reduceRight<number>((a, x) => a + x);
971+
expect(sum).toStrictEqual(6);
972+
});
973+
974+
test('reduce empty collection without initial value', () => {
975+
const coll = createCollection();
976+
expect(() => coll.reduceRight((a: number, x) => a + x)).toThrowError(
977+
new TypeError('Reduce of empty collection with no initial value'),
978+
);
979+
});
980+
});

‎packages/collection/src/collection.ts

+89
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,64 @@ export class Collection<K, V> extends Map<K, V> {
274274
return undefined;
275275
}
276276

277+
/**
278+
* Searches for a last item where the given function returns a truthy value. This behaves like
279+
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLast | Array.findLast()}.
280+
*
281+
* @param fn - The function to test with (should return a boolean)
282+
* @param thisArg - Value to use as `this` when executing the function
283+
*/
284+
public findLast<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;
285+
public findLast(fn: (value: V, key: K, collection: this) => unknown): V | undefined;
286+
public findLast<This, V2 extends V>(
287+
fn: (this: This, value: V, key: K, collection: this) => value is V2,
288+
thisArg: This,
289+
): V2 | undefined;
290+
public findLast<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;
291+
public findLast(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {
292+
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
293+
if (thisArg !== undefined) fn = fn.bind(thisArg);
294+
const entries = [...this.entries()];
295+
for (let index = entries.length - 1; index >= 0; index--) {
296+
const val = entries[index]![1];
297+
const key = entries[index]![0];
298+
if (fn(val, key, this)) return val;
299+
}
300+
301+
return undefined;
302+
}
303+
304+
/**
305+
* Searches for the key of a last item where the given function returns a truthy value. This behaves like
306+
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLastIndex | Array.findLastIndex()},
307+
* but returns the key rather than the positional index.
308+
*
309+
* @param fn - The function to test with (should return a boolean)
310+
* @param thisArg - Value to use as `this` when executing the function
311+
*/
312+
public findLastKey<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;
313+
public findLastKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;
314+
public findLastKey<This, K2 extends K>(
315+
fn: (this: This, value: V, key: K, collection: this) => key is K2,
316+
thisArg: This,
317+
): K2 | undefined;
318+
public findLastKey<This>(
319+
fn: (this: This, value: V, key: K, collection: this) => unknown,
320+
thisArg: This,
321+
): K | undefined;
322+
public findLastKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {
323+
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
324+
if (thisArg !== undefined) fn = fn.bind(thisArg);
325+
const entries = [...this.entries()];
326+
for (let index = entries.length - 1; index >= 0; index--) {
327+
const key = entries[index]![0];
328+
const val = entries[index]![1];
329+
if (fn(val, key, this)) return key;
330+
}
331+
332+
return undefined;
333+
}
334+
277335
/**
278336
* Removes items that satisfy the provided filter function.
279337
*
@@ -533,6 +591,37 @@ export class Collection<K, V> extends Map<K, V> {
533591
return accumulator;
534592
}
535593

594+
/**
595+
* Applies a function to produce a single value. Identical in behavior to
596+
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight | Array.reduceRight()}.
597+
*
598+
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `value`, `key`, and `collection`
599+
* @param initialValue - Starting value for the accumulator
600+
*/
601+
public reduceRight<T>(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {
602+
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
603+
const entries = [...this.entries()];
604+
let accumulator!: T;
605+
606+
let index: number;
607+
if (initialValue === undefined) {
608+
if (entries.length === 0) throw new TypeError('Reduce of empty collection with no initial value');
609+
accumulator = entries[entries.length - 1]![1] as unknown as T;
610+
index = entries.length - 1;
611+
} else {
612+
accumulator = initialValue;
613+
index = entries.length;
614+
}
615+
616+
while (--index >= 0) {
617+
const key = entries[index]![0];
618+
const val = entries[index]![1];
619+
accumulator = fn(accumulator, val, key, this);
620+
}
621+
622+
return accumulator;
623+
}
624+
536625
/**
537626
* Identical to
538627
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},

0 commit comments

Comments
 (0)
Please sign in to comment.