3 ms·
You can do that last one pretty easily in JS with a helper function. function by (key) { return function (obj) { return obj[key] }
by crooked-v 8y ago
You can do that last one pretty easily in JS with a helper function.
function by (key) {
return function (obj) {
return obj[key]
}
}
// sort(people, by('age'))
- repsilat 8y agoNot a bad solution. Having a top-level `by` function isn't a bad tradeoff if it's easily understood. For me there are two problems, though. Most importantly: 1. It doesn't generalise past lookups. Say I want to sort a list of numbers by their absolute value. In my spreadsheet language: sort(numbers, by: abs(numbers)) or filtering by some threshold: filter(numbers, by: numbers > threshold) Both are "repetitive" -- we might prefer something with first-class functions to get closer to a point-free style, but my users won't care. And the repetition isn't actually useless, there are times you might really want that flexibility: filter(users.id, by: users.age > 21) 2. My language isn't big on first-class functions. One day it might get support for them for some use-cases where you just need that flexibility[1], but in the meantime they don't provide a lot of value, and they're not a good fit for my hypothetical future users. If I told my hypothetical users that `by` returns a function, their response would probably be, "What is a function?" The unit of logic abstraction in my spreadsheet language is... slightly weird from a traditional programming perspective. Thanks again for commenting constructively, though -- seeing a new ergonomic way to approach this sort of problem (or even just "tricks that could become idioms") is really useful. [1]: If you needed to provide a 2-arg comparator to `sort` then a lambda would be much better -- my scheme would require you to evaluate the cross-product of comparisons, so sorting would have to take time O(n^2), which is no good. Thankfully single-item key functions seem sufficient for most purposes.