Skip to content
This repository was archived by the owner on Feb 9, 2022. It is now read-only.
This repository was archived by the owner on Feb 9, 2022. It is now read-only.

Add max() and sum() #37

@erikrose

Description

@erikrose

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions