Last active
November 13, 2016 16:07
-
-
Save eenblam/63d559cba58c26a210bd409b5b764ce6 to your computer and use it in GitHub Desktop.
Random FP examples illustrating syntactic sugar from ES2015. Toy problems, not optimized.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function empty(coll) { return 0 === coll.length; } | |
/** | |
* These one-liners are equivalent... | |
* But they're hard to read, and both are undefined on empty collections. :( | |
*/ | |
function reverse([h, ...t]) { return empty(t) ? h : reverse(t).concat(h); } | |
let reverse = ([h,...t]) => empty(t) ? h : reverse(t).concat(h); | |
/** | |
* Less pretty, but actually works on empty collections. | |
*/ | |
function reverse(coll) { | |
if (empty(coll)) return coll; | |
let [h,...t] = coll; | |
return empty(t) ? h : reverse(t).concat(h); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a different implementation, building on the one here:
This is a nice and non-recursive solution for arrays, but
reduce
isn't a method ofStr
!Even if we extended the prototype of
Str
, we would need a different implementation of thisreverse
function in order to pass an empty string,""
, instead of[]
asinitialValue
.And, type safety aside, if our function can't reverse strings, why not just call
arr.reverse()
?