Add iminBy and imaxBy
This commit is contained in:
parent
8fbb5c4ad1
commit
089920e4d3
|
@ -20,7 +20,9 @@ import {
|
||||||
imapfilter,
|
imapfilter,
|
||||||
imaterialize,
|
imaterialize,
|
||||||
imax,
|
imax,
|
||||||
|
imaxBy,
|
||||||
imin,
|
imin,
|
||||||
|
iminBy,
|
||||||
ipartition,
|
ipartition,
|
||||||
irange,
|
irange,
|
||||||
irecur,
|
irecur,
|
||||||
|
@ -340,5 +342,11 @@ describe("Iterators", () => {
|
||||||
|
|
||||||
expect(imax(IEMPTY)).toEqual(-Infinity);
|
expect(imax(IEMPTY)).toEqual(-Infinity);
|
||||||
expect(imax(iarray([3, 8, 2, 4]))).toEqual(8);
|
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
24
mod.ts
|
@ -516,3 +516,27 @@ export const imin = (iterable: Iterable<number>) =>
|
||||||
ireduce(iterable, Math.min, Infinity);
|
ireduce(iterable, Math.min, Infinity);
|
||||||
export const imax = (iterable: Iterable<number>) =>
|
export const imax = (iterable: Iterable<number>) =>
|
||||||
ireduce(iterable, Math.max, -Infinity);
|
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));
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue