Created
February 19, 2017 05:53
-
-
Save alejandrolechuga/4b5252ce80951bd0319ed97022ad7928 to your computer and use it in GitHub Desktop.
Functional Programming
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
// Notes from funfunfunction videos | |
/* | |
Functional programming | |
According to the video FP should improve your code, less time and more understandable, in javascript functions are values | |
*/ | |
// functions can be assigned to variables | |
var triple = function (x) { | |
return x * 3; | |
} | |
var waffle = triple; | |
waffle(2); | |
/* | |
What are high order functions , componsition. The fact that you can pass a function as a value allows you to compose functions | |
*/ | |
// For example filter | |
// list of animals | |
var animals = [ | |
{ name: 'Fluffykins', species: 'rabbit'}, | |
{ name: 'Caro', species: 'dog'}, | |
{ name: 'Halmiton', species: 'dog'}, | |
{ name: 'Harold', species: 'fish'}, | |
{ name: 'Ursula', species: 'cat'}, | |
{ name: 'Jimmy', species: 'fish'} | |
]; | |
// normal approach | |
var dogs = []; | |
for (var i = 0; i < animals.length; i++) {\ | |
if (animals[i].species === 'dog' ) { | |
dogs.push(animals[i]); | |
} | |
} | |
// fp way | |
var dogs = animals.filter(function(animal) { | |
return animal.species === 'dog'; // one line of logic | |
}); | |
// breaking down the logic | |
var isDog = function(animal) { | |
return animal.species === 'dog'; | |
}; | |
var isNotDog = function(animal) { | |
return animal.species !== 'dog'; | |
}; | |
// composition | |
var dogs = animals.filter(isDog); | |
var otherAnimals = animals.filter(isNotDog); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment