This repository was archived by the owner on Feb 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
This repository was archived by the owner on Feb 9, 2022. It is now read-only.
Add max() and sum() #37
Copy link
Copy link
Open
Description
I just switched https://github.com/mozilla/fathom from lodash to wu because lodash isn't very interested in supporting ES6 iterables. However, that meant I had to bring my own max() and sum() functions. Would you consider a PR for them in wu? I wrote them so they're polymorphic, able to be used on numbers, strings, or whatever supports the > operator, without any undue casting influence from a static initializer.
// Return the maximum item from an iterable, as defined by >.
//
// Works with any type that works with >. If multiple items are equally great,
// return the first.
//
// by: a function that, given an item of the iterable, returns a value to
// compare
function max(iterable, by = identity) {
let maxSoFar, maxKeySoFar;
let isFirst = true;
forEach(
function (item) {
const key = by(item);
if (key > maxKeySoFar || isFirst) {
maxSoFar = item;
maxKeySoFar = key;
isFirst = false;
}
},
iterable);
return maxSoFar;
}
function identity(x) {
return x;
}// Return the sum of an iterable, as defined by the + operator.
function sum(iterable) {
let total;
let isFirst = true;
forEach(
function assignOrAdd(addend) {
if (isFirst) {
total = addend;
isFirst = false;
} else {
total += addend;
}
},
iterable);
return total;
}Thanks for considering, and thanks for filling a big hole with wu!
Metadata
Metadata
Assignees
Labels
No labels