OK I know I’ve been promising you more about ‘this’ and I will come back to it in my next post.
So with this kata I had to write a processArray function which would take an array and a callback function as parameters. The callback function would be applied to every element in the array. So for example:
Array
[4, 8, 2, 7, 5]
after processing with functionvar myArray = [4, 8, 2, 7, 5];
myArray = processArray(myArray,function (a) {
return a * 2;
});
//will be
[ 8, 16, 4, 14, 10 ]
.And
Array
[7, 8, 9, 1, 2]
after processing with functionvar myArray = [7, 8, 9, 1, 2];
myArray = processArray(myArray, function (a) {
return a + 5;
});
//will be[ 12, 13, 14, 6, 7 ]
.
I did this:
function processArray(arr, callback) {
var arrMine =[];
for (var i=0; i<arr.length; i++) {
arrMine.push(callback(arr[i]));
}
return arrMine;
}
So I thought this was not a bad I had all the bases covered with this solution and it was not as messy as last time. However I did not even consider the map function, something I had come across but not even considered. This was the most upvoted solution.
function processArray(arr, callback) {
return arr.map(callback);
}
Once again simple elegant and much less code than mine. While that was good, this just blew me away:
const processArray = (a, fn) => a.map(fn);
One word – WOW! I don’t even know where to begin. I looked at it for a while and thought will I get to a level like that, I think I may do but it will be a while. The journey continues