Created
October 17, 2017 14:56
-
-
Save marsicdev/898f102fa0830b6c3c4ebbcb831df173 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In our example, the first function, multiplyByTwo(), | |
// accepts three parameters, loops through them, | |
// multiplies them by two, and returns an array | |
// containing the result. | |
function multiplyByTwo(a, b, c) { | |
var outputArray = []; | |
for (var i = 0; i < arguments.length; i++) { | |
var currentElement = arguments[i]; | |
outputArray[i] = currentElement * 2; | |
} | |
return outputArray; | |
} | |
function addOne(a) { | |
return a + 1; | |
} | |
// Test these functions: | |
var output1 = multiplyByTwo(1, 2, 3); | |
var output2 = addOne(100); | |
console.log(output1); | |
console.log(output2); | |
// Now let's say you want to have an array, myarr, | |
// that contains three elements, and each of the | |
// elements is to be passed through both functions. | |
var myArray = []; | |
myArray = multiplyByTwo(10, 20, 30); | |
// [20, 40, 60] | |
// loop through each element, passing it to addOne() | |
for (var i = 0; i < myArray.length; i++) { | |
myArray[i] = addOne(myArray[i]); | |
} | |
console.log(myArray); | |
// output > [21, 41, 61] | |
// Everything works ne, but there's room for improvement. | |
function multiplyByTwo2(a, b, c, callback) { | |
var outputArray = []; | |
for (var i = 0; i < arguments.length - 1; i++) { | |
var currentElementTimes2 = arguments[i] * 2; | |
var element = callback(currentElementTimes2); | |
outputArray[i] = element; | |
} | |
return outputArray; | |
} | |
// By using the modified function, all the work is done | |
// with just one function call, which passes the start | |
// values and the callback function: | |
myArray = multiplyByTwo2(1, 2, 3, addOne); | |
console.log(myArray); | |
// Instead of defining addOne(), you can use an anonymous function, | |
// therefore saving an extra global variable | |
multiplyByTwo(1, 2, 3, function (a) { | |
return a + 1; | |
}); | |
// Anonymous functions are easy to change should the need arise | |
var multipleBy10 = function (a) { | |
return a * 10; | |
}; | |
multiplyByTwo(1, 2, 3, multipleBy10); | |
multiplyByTwo(1, 2, 3, function (a) { | |
return a * 100; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment