This proposal introduces two new Iterator.prototype
helper methods which are meant to be a specialized usage of Array.prototype.reduce
:
Iterator.prototype.findMin<T>( comparatorFn: ( valueA: T, valueB: T ): -1|0|1): T | undefined
- find "the smallest" value within a collection, according to a custom order (defined by a comparator function which is the same asArray.prototype.sort
's callback as defined in23.1.3.30 Array.prototype.sort ( comparefn )
in ES2023 specs)Iterator.prototype.findMax<T>( comparatorFn: ( valueA: T, valueB: T ): -1|0|1): T | undefined
- same as above, but "the biggest".
EXAMPLE
function* peopleGen() {
yield {name: "Adam", age: 15};
yield {name: "John", age: 40};
yield {name: "Lisa", age: 23};
}
const result = peopleGen()
.findMax((a, b) => a.age - b.age);
result.next(); // {value: {name: "Adam", age: 15}, done: false};
result.next(); // {value: {name: "John", age: 40}, done: false};
result.next(); // {value: {name: "John", age: 40}, done: false};
POLYFILL
not sure if the polyfill is available before Iterator.prototype becomes available.
BEFORE
Currently we can achieve it by running the Array.prototype.reduce
, where the current accumulator is the currently biggest/smallest item out of entire collection:
var people = [
{name: "Adam", age: 15},
{name: "John", age: 40},
{name: "Lisa", age: 23}
];
var theYoungest = people.reduce((minSoFar, item) => {
if (minSoFar.age < item.age){ // earlier in order
return minSoFar
} else if (minSoFar.age > item.age){ // later in order
return item
} else { // equal in order
return minSoFar
}
});
The solution currently is perfectly available, though there's no abstraction to extract the comparatorFn which is reusable across .findMin
, .findMax
and .sort
array methods.
AFTER
var people = [
{name: "Adam", age: 15},
{name: "John", age: 40},
{name: "Lisa", age: 23}
];
// var iterator = people.values()
var theYoungest = people.values().findMin((a, b) => a.age - b.age); // {name: "Adam", age: 15}
var theOldest = people.values().findMax((a, b) => a.age - b.age); // {name: "John", age: 40}