Using functions in FP ways
There are several common coding patterns that actually take advantage of FP style, even if you weren't aware of it. Let's then get to examine them, and point out the functional aspects of the code, so you can get more accustomed to this coding style.
Injection - sorting it out
A first example of passing functions as parameters is provided by the Array.prototype.sort()
method. If you have an array of strings, and you want to sort it, you can just use something like the following code. For example, to alphabetically sort an array with the colors of the rainbow:
var colors = [
"violet",
"indigo",
"blue",
"green",
"yellow",
"orange",
"red"
];
colors.sort();
console.log(colors);
// ["blue", "green", "indigo", "orange", "red", "violet", "yellow"]
Note that we didn't have to provide any parameters to the .sort()
call, but the array got sorted perfectly well. By default, this method sorts strings according to their ASCII internal representation...