From the code below, is it clear enough, what am I doing and what is each variable representing?
//Work out the first ten digits of the sum of the following
//large nums
function largeSum(arr) {
return Number(arr.map(
textNum => textNum.substring(0, 11)
).reduce(
(sum, textChunkofNum) => sum + Number(textChunkofNum), 0
).toString().slice(0, 10));
}
Got it. You propose use each line for every method.
I thought it would be readable enough, if two methods are placed in one line, if they don’t have much inside parenthesis
toString().slice(0, 10))
arr parameter could be easily renamed, I guess largeNums would be ok.
To add example of function call - also totally makes sense.
I didn’t change name of the function, in order to pass the tests in the challenge step.
If my aim is to make the code more readable, beside clear naming, id also warp different parts of the code into variables and make the calculations before i give the result to return. For example you can take out the callbacks you pass to each method and use a name on what its prupose is.
// unsure of the purpose of this callback, so i called it mapper...
const mapper = textNum => textNum.substring(0, 11)
arr.map(mapper)
Also if you have reduce in the equation, usually you can include whats done in the map method directly in the reduce.
// again, dont get focused on my naming
const chunkify = textNum => textNum.substring(0, 11)
reduce((sum, textNum) => sum + Number(chunkify(textNum)), 0)
Eh, I’m not wild about creating a bunch temporary variables. You increase the number of places that you need to change stuff in an update. Also, it leaves you bouncing around to understand the logical flow.
Chaining is good thing. Use good variable names inside of the chaining to make it clear what each step does.
In compiled languages, chaining can help the compiler optimize out intermediate data structures.