/
min.js
41 lines (35 loc) · 1.11 KB
/
min.js
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
import {iter} from '../base/iter.js';
/**
* Returns the smallest element of the input iterable according
* to some comparison function.
*
* @example
* min( ( a , b ) => a - b , range( 10 ) ) ; // returns 0
*
* @example
* min( ( a , b ) => a - b , range( 0 ) ) ; // returns undefined
*
* @param {Function} compare - The comparison function to use. This function
* must be 2-ary. It must return -1, 0, or 1 depending whether the first
* parameter is, respectively, less than, equal to, or greater than the second
* parameter.
* @param {Iterable} iterable - The input iterable.
* @param {Object} [dflt=undefined] - The default value to return in the case
* that the input iterable is empty.
* @returns {Object} The smallest element of <code>iterable</code> according to
* <code>compare</code>.
*/
export function min(compare, iterable, dflt = undefined) {
const iterator = iter(iterable);
const first = iterator.next();
if (first.done) {
return dflt;
}
let smallest = first.value;
for (const candidate of iterator) {
if (compare(candidate, smallest) < 0) {
smallest = candidate;
}
}
return smallest;
}