getify / Functional-Light-JS

Pragmatic, balanced FP in JavaScript. @FLJSBook on twitter.
http://FLJSBook.com
Other
16.6k stars 1.96k forks source link

Chapter 9: not getting the standalone implementation reducer function #188

Closed qianist closed 8 months ago

qianist commented 5 years ago

Quote:

But a standalone implementation of reduce(..) might look like this:

function reduce(reducerFn,initialValue,arr) {
    var acc, startIdx;

    if (arguments.length == 3) {
        acc = initialValue;
        startIdx = 0;
    }
    else if (arr.length > 0) {
        acc = arr[0];
        startIdx = 1;
    }
    else {
        throw new Error( "Must provide at least one value." );
    }

    for (let idx = startIdx; idx < arr.length; idx++) {
        acc = reducerFn( acc, arr[idx], idx, arr );
    }

    return acc;
}

Question:

Perhaps I don't understand the context, but how to call this function without passing an initialValue?

baekhyunee7 commented 4 years ago

maybe some details is omitted,rewrite it else if (arr=initialValue,arr.length > 0) {

kyletannv commented 8 months ago

From Appendix A:

With traditional library implementations of reduce(..) (like Ramda), the initial value parameter is in the middle, and not optional.

His library (FPO) makes it optional:

FPO's reduce(..) method can take the arguments in any order, and you can omit the optional initial value if desired.