Functional Programming in Javascript
About
Code - Functional programming (FP) - Collection Operations in javascript.
All functional programming functions are array operations - See Doc
Example
To get the cookies
console.log("Functional Programming: The cookies that we see with Javascript");
document.cookie
.split(";")
.map(cookie => cookie.split("="))
.forEach(cookie=>console.log(cookie));
List
Collector
All function returns an array.
A few returns an element such as:
- find: returns the value of the first element in the provided array that satisfies the provided testing function.
- findIndex() method returns the index of the first element in the array that satisfies the provided testing function.
map
Javascript - Map function (Functional programming)
Map example 1
data = [
{ name: 'Nicolas', firstname: 'Gerard', surname: 'nico' },
{ name: 'Rixt', firstname: 'Van Der Veen', surname: 'konigin' }
]
console.log("Name");
names = data.map( function (d) { return d.name } )
console.log(names);
console.log("FirstName");
firstnames = data.map( function (d) { return d.firstname } )
console.log(firstnames);
console.log("Surname");
surnames = data.map( function (d) { return d.surname } )
console.log(surnames);
Map example 2 - select and process
var myList = [].slice.call(document.querySelectorAll('selector'))
myList.map(function (element) {
// ....
});
Filter
filter functional programming function.
Example a split on a string that does contains a separator without value create an empty string element. We filter it below.
let s = "aStringWithoutSeparator.";
console.log("With filtering");
console.log( s.split ('.').filter(el => {return el.length != 0}));
console.log("Without filtering");
console.log(s.split ('.'))
Terminal
terminal function are all array function that does not produce an array such as: