From ecd67dc56330f6787be56b717ba200fe3ef23ec5 Mon Sep 17 00:00:00 2001 From: kirillgroshkov Date: Tue, 5 Mar 2024 19:31:53 +0100 Subject: [PATCH] feat: _minBy/_maxBy now supports string comparisons Previously only number comparisons were available --- src/array/array.util.test.ts | 4 ++++ src/array/array.util.ts | 12 ++++++------ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/array/array.util.test.ts b/src/array/array.util.test.ts index 3b0e64ab..59cd7850 100644 --- a/src/array/array.util.test.ts +++ b/src/array/array.util.test.ts @@ -387,6 +387,10 @@ test('_maxBy, _minBy', () => { ) expect(_minByOrUndefined([{ age: 18 }, { age: 30 }], u => u.age)).toEqual({ age: 18 }) expect(_minBy([{ age: 18 }, { age: 30 }], u => u.age)).toEqual({ age: 18 }) + + expect(_minBy([{ date: '2023-06-22' }, { date: '2023-06-21' }], u => u.date)).toEqual({ + date: '2023-06-21', + }) }) test('_zip', () => { diff --git a/src/array/array.util.ts b/src/array/array.util.ts index 3cc34bec..1fe4b421 100644 --- a/src/array/array.util.ts +++ b/src/array/array.util.ts @@ -395,13 +395,13 @@ export function _max(array: T[]): NonNullable { return a.reduce((max, item) => (max >= item ? max : item)) } -export function _maxBy(array: T[], mapper: Mapper): T { +export function _maxBy(array: T[], mapper: Mapper): T { const max = _maxByOrUndefined(array, mapper) if (max === undefined) throw new Error(`_maxBy returned undefined`) return max } -export function _minBy(array: T[], mapper: Mapper): T { +export function _minBy(array: T[], mapper: Mapper): T { const min = _minByOrUndefined(array, mapper) if (min === undefined) throw new Error(`_minBy returned undefined`) return min @@ -411,11 +411,11 @@ export function _minBy(array: T[], mapper: Mapper): T export function _maxByOrUndefined( array: T[], - mapper: Mapper, + mapper: Mapper, ): T | undefined { if (!array.length) return let maxItem: T | undefined - let max: number | undefined + let max: number | string | undefined array.forEach((item, i) => { const v = mapper(item, i) if (v !== undefined && (max === undefined || v > max)) { @@ -429,11 +429,11 @@ export function _maxByOrUndefined( export function _minByOrUndefined( array: T[], - mapper: Mapper, + mapper: Mapper, ): T | undefined { if (!array.length) return let minItem: T | undefined - let min: number | undefined + let min: number | string | undefined array.forEach((item, i) => { const v = mapper(item, i) if (v !== undefined && (min === undefined || v < min)) {