Ooh, this could be a challenge, of how to rework the code so that it’s easier to understand.
First in arrayCalc, we can use a temporary variable for each array item, which makes it easier to step to forEach later on.
function arrayCalc(arr, fn) {
var arrRes = [];
for (var c = 0; c < arr.length; c++) {
var item = arr[c];
arrRes.push(fn(item));
}
return arrRes;
}
we can now easily use forEach instead of the for loop.
function arrayCalc(arr, fn) {
var arrRes = [];
// for (var c = 0; c < arr.length; c++) {
// var item = arr[c];
arr.forEach(function (item) {
arrRes.push(fn(item));
});
// }
return arrRes;
}
And we can avoid making changes to a variable external to the forEach loop, by using map instead to build up the array.
function arrayCalc(arr, fn) {
var arrRes = arr.map(function (item) {
return fn(item);
});
return arrRes;
}
And we are no longer doing anything with arrRes
, so we can just return the map.
function arrayCalc(arr, fn) {
// var arrRes = arr.map(function (item) {
return arr.map(function (item) {
return fn(item);
});
// return arrRes;
}
And instead of the function that we use with the map method, we can just use the fn
function itself.
function arrayCalc(arr, fn) {
return arr.map(fn);
}
And we could even remove the arrayCalc function completely by moving that map method down to the ages calculation.
// function arrayCalc(arr, fn) {
// return arr.map(fn);
// }
function calculateAge(el) {
return 2020 - el;
}
// var ages = arrayCalc(years, calculateAge);
var ages = years.map(calculateAge);
And instead of that calculateAge function, we could use arrow-notation instead:
// function calculateAge(el) {
// return 2020 - el;
// }
var calculateAge = (el) => 2020 - el;
var ages = years.map(calculateAge);
And we can rename that misleading el
variable so that it’s more meaningfully named:
var calculateAge = (year) => 2020 - year;
var ages = years.map(calculateAge);
And we can even move that arrow-notation into the map method:
// var calculateAge = (year) => 2020 - year;
// var ages = years.map(calculateAge);
var ages = years.map(year => 2020 - year);
Summary
The code started off as the following code:
function arrayCalc(arr, fn) {
var arrRes = [];
for (var c = 0; c < arr.length; c++) {
arrRes.push(fn(arr[c]));
}
return arrRes;
}
function calculateAge(el) {
return 2020 - el;
}
var ages = arrayCalc(years, calculateAge);
And has been gradually improved to this much simpler single line of code:
var ages = years.map(year => 2020 - year);
Is that single line instead of 11 an improvement? I think so.