fitzgen / wu.js

wu.js is a JavaScript library providing higher order functions for ES6 iterators.
http://fitzgen.github.com/wu.js/
MIT License
864 stars 32 forks source link

Add max() and sum() #37

Open erikrose opened 8 years ago

erikrose commented 8 years ago

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!

fitzgen commented 8 years ago

Sure, I would accept a PR with these methods and test coverage for them.

I think that by should instead be a -1 | 0 | 1 style comparator function, like what Array.prototype.sort takes.

DanielSWolf commented 7 years ago

👍 While you're at it, complementing max with min would be nice!