Skip to content

Instantly share code, notes, and snippets.

@eenblam
Last active November 13, 2016 16:07
Show Gist options
  • Save eenblam/63d559cba58c26a210bd409b5b764ce6 to your computer and use it in GitHub Desktop.
Save eenblam/63d559cba58c26a210bd409b5b764ce6 to your computer and use it in GitHub Desktop.
Random FP examples illustrating syntactic sugar from ES2015. Toy problems, not optimized.
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);
}
@eenblam
Copy link
Author

eenblam commented Nov 13, 2016

Here's a different implementation, building on the one here:

function reverse (arr) {
  return arr.reduce((acc, x) => [x].concat(acc), []);
}

This is a nice and non-recursive solution for arrays, but reduce isn't a method of Str!

Even if we extended the prototype of Str, we would need a different implementation of this reverse function in order to pass an empty string, "", instead of [] as initialValue.

And, type safety aside, if our function can't reverse strings, why not just call arr.reverse()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment