forked from remeda/remeda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxBy.ts
75 lines (69 loc) · 1.71 KB
/
maxBy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { purry } from './purry';
import { PredIndexed, PredIndexedOptional } from './_types';
const _maxBy =
(indexed: boolean) =>
<T>(array: Array<T>, fn: PredIndexedOptional<T, number>) => {
let ret: T | undefined = undefined;
let retMax: number | undefined = undefined;
array.forEach((item, i) => {
const max = indexed ? fn(item, i, array) : fn(item);
if (retMax === undefined || max > retMax) {
ret = item;
retMax = max;
}
});
return ret;
};
/**
* Returns the max element using the provided predicate.
* @param fn the predicate
* @signature
* R.maxBy(fn)(array)
* R.maxBy.indexed(fn)(array)
* @example
* R.pipe(
* [{a: 5}, {a: 1}, {a: 3}],
* R.maxBy(x => x.a)
* ) // { a: 5 }
* @data_last
* @indexed
* @category Array
*/
export function maxBy<T>(
fn: (item: T) => number
): (items: ReadonlyArray<T>) => T | undefined;
/**
* Returns the max element using the provided predicate.
* @param items the array
* @param fn the predicate
* @signature
* R.maxBy(array, fn)
* R.maxBy.indexed(array, fn)
* @example
* R.maxBy(
* [{a: 5}, {a: 1}, {a: 3}],
* x => x.a
* ) // { a: 5 }
* @data_first
* @indexed
* @category Array
*/
export function maxBy<T>(
items: ReadonlyArray<T>,
fn: (item: T) => number
): T | undefined;
export function maxBy() {
return purry(_maxBy(false), arguments);
}
export namespace maxBy {
export function indexed<T>(
array: ReadonlyArray<T>,
fn: PredIndexed<T, number>
): T | undefined;
export function indexed<T>(
fn: PredIndexed<T, number>
): (array: ReadonlyArray<T>) => T | undefined;
export function indexed() {
return purry(_maxBy(true), arguments);
}
}