Writing concise, readable arrow functions

I use Codewars and similar to warm up. When I tried writing solutions as concisely as possible, my colleague noted that my function (which finds the element of an array that produces the largest result when passed in a callback) was definitely short, but unintuitive.

const maxBy = (arr, callback) => arr.reduce((max, el) => callback(el) > max.val ? {val: callback(el), el} : max, {val: -Infinity, el: undefined}).el;

Though conciseness is lovely, it’s not really helpful if it means my code isn’t easily parseable by whomever looks at it next. Airbnb has some opinions on cases like this, but they’re a bit less verbose compared to their guide on functions in general. That said, their suggestions can go a long way.

First, lets add parentheses. Adding parens definitely helps with clearing up the comma after max and before reduce’s second argument.

const maxBy = (arr, callback) => (arr.reduce((max, el) => (callback(el) > max.val ? {val: callback(el), el} : max), {val: -Infinity, el: undefined}).el);

There are actually two functions being defined in here, maxBy and the anonymous callback for reduce. Let’s break those functions into their own lines.

const maxBy = (arr, callback) => (
arr.reduce((max, el) => (
callback(el) > max.val ? {val: callback(el), el} : max
), {val: -Infinity, el: undefined}).el
);

A lot better! That third line is may be approaching the limit of what should be on one line. We can deviate a little from Airbnb and split it across multiple lines.

const maxBy = (arr, callback) => (
arr.reduce((max, el) => (
callback(el) > max.val
? {val: callback(el), el}
: max
), {val: -Infinity, el: undefined}).el
);

Not sure about that dangling .el at the end. Maybe this shouldn’t necessarily be a one-line solution, but it’s fun to write it that way. Always open to suggestions, too.