Add iminBy and imaxBy

This commit is contained in:
Michaël Lemaire 2021-08-30 23:07:44 +02:00
parent 8fbb5c4ad1
commit 089920e4d3
2 changed files with 32 additions and 0 deletions

View file

@ -20,7 +20,9 @@ import {
imapfilter,
imaterialize,
imax,
imaxBy,
imin,
iminBy,
ipartition,
irange,
irecur,
@ -340,5 +342,11 @@ describe("Iterators", () => {
expect(imax(IEMPTY)).toEqual(-Infinity);
expect(imax(iarray([3, 8, 2, 4]))).toEqual(8);
expect(iminBy(IEMPTY, (x) => x)).toBeUndefined();
expect(iminBy(["aaa", "b", "cc"], (x) => x.length)).toEqual("b");
expect(imaxBy(IEMPTY, (x) => x)).toBeUndefined();
expect(imaxBy(["aaa", "b", "cc"], (x) => x.length)).toEqual("aaa");
});
});

24
mod.ts
View file

@ -516,3 +516,27 @@ export const imin = (iterable: Iterable<number>) =>
ireduce(iterable, Math.min, Infinity);
export const imax = (iterable: Iterable<number>) =>
ireduce(iterable, Math.max, -Infinity);
/**
* Min/max by key function
*/
export function iminBy<T>(
iterable: Iterable<T>,
key: (value: T) => number,
): T | undefined {
return ireduce(
iterable,
(item1, item2) =>
(typeof item1 == "undefined" || typeof item2 == "undefined") ||
(key(item1) > key(item2))
? item2
: item1,
undefined,
);
}
export function imaxBy<T>(
iterable: Iterable<T>,
key: (value: T) => number,
): T | undefined {
return iminBy(iterable, (value) => -key(value));
}