Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created October 23, 2020 00:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/ebbf831df8a05f0438e898f8a52bc7fe to your computer and use it in GitHub Desktop.
Save ryanflorence/ebbf831df8a05f0438e898f8a52bc7fe to your computer and use it in GitHub Desktop.
// don't clutter up lines with function blocks
let obj = items.reduce((memo, item) => {
memo[item.id] = item.name;
return memo;
});
// just use the comma operator for super clean code!
let obj = items.reduce((memo, item) => (memo[item.id] = item.name, memo));
// lol
@pkoch
Copy link

pkoch commented Oct 25, 2020

I'd also like to point out there's a strong factor of education and familiarity here. It took me as long to understand both lukeshiru's snippets. Not because I'm ✨ mEgA ✨ SmaRT ✨ but just because I'm already accustomed to both styles. Familiarity is a hurdle to overcome to be able to get our hands on more tools.

I think the best way of thinking about this is as if it was another "sub-language" with its own standard library. Bear with me for a little while. For example, in a functional code base, I'd expect some concepts to be available. Namely:

  • const pluck = (...keys) => obj => keys.map(k => obj[key])
  • const map => f => iterable => iterable.map(f)
  • const pipe => (...fns) => fns.reduce((a, f) => x => f(a(x)), x => x)
  • const pipeValue => (obj, ...fns) => pipe(...fns)(obj)

I can already hear you say "pkoch, that's a bunch of arrow soup, and it's not helping me". To which I say, well, yes, for now, but that was the alien part (and it's something that you can code and test in an hour). You only really need to know what the names are, and they let me pull off the following trick.

You know how everyone gets their panties in a knot when they see Elixir code like this:

items
|> Enum.map(Map.take(&1, [:id, :name]))
|> Map.new

Well, with the functions I've introduced, you can do something similar. It looks like this:

pipeValue(
  items,
  map(pluck(['id', 'name'])),
  Object.fromEntries,
)

I will never think any for loop is more readable than this pipeValue version. Perhaps the reverse is true for you, but I hope I have demonstrated why this style works well for me.

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