Skip to content

Commit

Permalink
feat: _minBy/_maxBy now supports string comparisons
Browse files Browse the repository at this point in the history
Previously only number comparisons were available
  • Loading branch information
kirillgroshkov committed Mar 5, 2024
1 parent 533fda0 commit ecd67dc
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
4 changes: 4 additions & 0 deletions src/array/array.util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
12 changes: 6 additions & 6 deletions src/array/array.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,13 +395,13 @@ export function _max<T>(array: T[]): NonNullable<T> {
return a.reduce((max, item) => (max >= item ? max : item))
}

export function _maxBy<T>(array: T[], mapper: Mapper<T, number | undefined>): T {
export function _maxBy<T>(array: T[], mapper: Mapper<T, number | string | undefined>): T {
const max = _maxByOrUndefined(array, mapper)
if (max === undefined) throw new Error(`_maxBy returned undefined`)
return max
}

export function _minBy<T>(array: T[], mapper: Mapper<T, number | undefined>): T {
export function _minBy<T>(array: T[], mapper: Mapper<T, number | string | undefined>): T {
const min = _minByOrUndefined(array, mapper)
if (min === undefined) throw new Error(`_minBy returned undefined`)
return min
Expand All @@ -411,11 +411,11 @@ export function _minBy<T>(array: T[], mapper: Mapper<T, number | undefined>): T

export function _maxByOrUndefined<T>(
array: T[],
mapper: Mapper<T, number | undefined>,
mapper: Mapper<T, number | string | undefined>,
): 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)) {
Expand All @@ -429,11 +429,11 @@ export function _maxByOrUndefined<T>(

export function _minByOrUndefined<T>(
array: T[],
mapper: Mapper<T, number | undefined>,
mapper: Mapper<T, number | string | undefined>,
): 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)) {
Expand Down

0 comments on commit ecd67dc

Please sign in to comment.