getify / Functional-Light-JS

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

Redundant fns.slice() in compose example #111

Closed EvgenyOrekhov closed 7 years ago

EvgenyOrekhov commented 7 years ago

In https://github.com/getify/Functional-Light-JS/blob/master/ch4.md#general-composition you have this piece of code:

function compose(...fns) {
    return function composed(result){
        // copy the array of functions
        var list = fns.slice();

Why copy the fns array if it's local to the compose function? Nobody outside compose can have a reference to it.

getify commented 7 years ago

It's not redundant, it's very necessary. But it's a bit sneaky why.

Nobody outside compose can have a reference to it.

That's the part that's sneaky. composed(..) (which is the returned composed function) has a reference to it, and for this particular implementation, composed(..) mutates the list with .pop(..). This is a problem if you try to use the returned composed function more than once.

Here's proof:

screen shot 2017-09-08 at 7 49 51 am

The list = fns.slice() ensures in the original code listing ensures each time that fns isn't modified, so the composed function can keep being used as often as needed.

EvgenyOrekhov commented 7 years ago

@getify Got it! Thank you for a prompt and detailed explanation!

getify commented 7 years ago

See above commit: I took this opportunity to call out this point of confusion you brought up. It's subtle enough that it deserves direct attention. Thanks!