getify / Functional-Light-JS

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

ch9: fix a code bug for the flatten #119

Closed blacktail closed 6 years ago

blacktail commented 6 years ago

Yes, I promise I've read the Contributions Guidelines (please feel free to remove this line IF YOU ACTUALLY READ THEM).

This sentence can not make the value flattened properly, because the result won't be flattened automatically.

[ ...list, Array.isArray( v ) ? flatten( v ) : v ]

Maybe we can use spread operator to the flatten(v) like below, but it will have syntax errors. Like the function return, we can not return multiple values for an expression.

[ ...list, ...(Array.isArray( v ) ? ...(flatten( v )) : v ]

We can also try to put spread operator here, but it will cause errors when the v is not an array.

[ ...list, ...(Array.isArray( v ) ? flatten( v ) : v) ]

So, we need to change v to an array. got this

[ ...list, ...(Array.isArray( v ) ? flatten( v ) : [v]) ]

And because ... has the lowest precedence(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence), we can write like this:

 [ ...list, ...Array.isArray( v ) ? flatten( v ) : [v] ]
getify commented 6 years ago

thanks for catching these mistakes... they're from an earlier commit where I had switched from concat(..) to the ..., but in the cases where I want flattening, I need the concat(..) in there to do the flattening part, which ... alone can't do (since it can't show up inside a ternary). I rolled those both back to using concat(..).