diff --git a/mod.test.ts b/mod.test.ts index f1facf5..359168b 100644 --- a/mod.test.ts +++ b/mod.test.ts @@ -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"); }); }); diff --git a/mod.ts b/mod.ts index c2c0eb8..5e3b0f4 100644 --- a/mod.ts +++ b/mod.ts @@ -516,3 +516,27 @@ export const imin = (iterable: Iterable) => ireduce(iterable, Math.min, Infinity); export const imax = (iterable: Iterable) => ireduce(iterable, Math.max, -Infinity); + +/** + * Min/max by key function + */ +export function iminBy( + iterable: Iterable, + 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( + iterable: Iterable, + key: (value: T) => number, +): T | undefined { + return iminBy(iterable, (value) => -key(value)); +}