Functional programming - NathanNeelis/frontend-data GitHub Wiki
So what is functional programming in a nutshell?
In functional programming, you try to keep the data separate from the functions.
So I will write a function, for example, to convert all items in an array to lowercase.
function toLowerCase(arr) {
let newCleanData = arr.map(x => x.toLowerCase());
return newCleanData;
}
This function has a parameter called arr. This is the array where this function will convert all items to lowercase.
Because it is a parameter, I can use this function for multiple datasets like this:
let eyeColorDataLowerCase = toLowerCase(array1);
let otherDataLowerCase = toLowerCase(array2);
So functional programming lets me use functions on different sets of data. You can say it's reusable.
Higher order functions
Filter
Filter is a method that loops over an array and creates a new (filtered) array. The filter function uses another function, also called a callback, to create this new array with only the requested items.
Here is an example of the filter function with an original for loop
function removeEmptySlots(arr){
let cleanData = [];
for (let i = 0; i < arr.lenght; i++) {
if (arr[i] != ""){
cleanData.push(arr[i]);
}
}
}
Here is the same example but then written with the filter method:
function removeEmptySlots(arr){
let cleanData = arr.filter(function (cleanData) {
return cleanData != "";
})
}
You can write this code even shorter:
function removeEmptySlots(arr){
let cleanData = arr.filter(keys => keys != "");
}
Notice how I put this method in a separate function? The reason for this is that I now can reuse this function on other datasets as well.
Map
Map is another higher-order function. Like filter, it loops through an array, but it creates a new array of all the values of a specific property. In this example I will be creating a new array with all empty spaces in strings removed. For this I will also be using the .replace() method.
Example with the old code:
function removeSpaces(arr){
let cleanData = [];
for (let i = 0; i < arr.length; i++) {
cleanData.push(arr[i].replace(/ /, ''));
}
}
Example using map method:
function removeSpaces(arr){
let cleanData = arr.map(
keys => {
return keys.replace(/ /, '')
});
}
Or in short:
function removeSpaces(arr){
let cleanData= arr.map(keys => keys.replace(/ /, ''));
}
Notice how I put this method in a separate function? The reason for this is that I now can reuse this function on other datasets as well.