-
-
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 |
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.
@saykatsu I'm on the vibe that DRY and KISS are good principles, yes. The thing is:
... having that behavior abstracted away in a function makes it far easier to test, maintain, read, and so on 😄