The current snippets are designed to be short/brief, but at the cost of sacrificing legibility. For example, the first snippet is:
arrayMax
Returns the maximum value in an array.
Use Math.max() combined with the spread operator (...) to get the maximum value in the array.
const arrayMax = arr => Math.max(...arr);`
// arrayMax([10, 1, 5]) -> 10
I noticed when copy/pasting, the comments kinda got in the way. Ideally, you'd want to separate the definition and the usage.
Additionally, the description is a bit lackluster. Why is the spread operator and Math.max() being used? If you know how it works, then it's obvious, but to new developers reading the code they probably don't know what's happening.
I suggest you keep the what
of the function at the top, then add a comprehensive how
beneath.
arrayMax
Returns the maximum value in an array.
const arrayMax = arr => Math.max(...arr);
Usage
arrayMax([10, 5, -2, 11, 0]); // 11
Explanation
Math.max()
returns the largest value given to it, accepting each value as a separate argument. For example, Math.max(1, 5, 3, 0)
returns 5
. However, it doesn't take an array of values - they must be supplied as separate arguments.
To find the largest value of an array, we can use the spread ...
operator.
Math.max(...[1, 5, 3, 0])
is the same as Math.max(1, 5, 3, 0)
. The spread operator "spreads" the values of the array into the function as separate arguments, which returns the largest value, thus returning the largest value of an array.
The clear downside of this is decreased information density. Ideally you'd have the usage and explanation collapsed, only to be expanded if necessary, but that's not possible(?) with MD. But it seems like a perfect opportunity for the website. But then you have 2 different versions ๐
Thoughts/ideas?