Created
June 20, 2016 11:56
-
-
Save alexcanessa/988036c04f48a7cc2cc05824990bf4cd to your computer and use it in GitHub Desktop.
Functional programming snippets
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
// Non functional programming way | |
function findLongestWord(arr) { | |
var max = Number.NEGATIVE_INFINITY; | |
for (var i = 0; i < arr.length; i++) { | |
if (arr[i].length > max) { | |
max = arr[i].length; | |
} | |
} | |
return max; | |
} | |
var arr = ['a', 'bbb', 'hellociao']; | |
findLongestWord(arr); | |
// Functional programming way | |
function getLength(word) { | |
return word.length; | |
} | |
function findMax(a, b) { | |
return Math.max(a, b); | |
} | |
function findLongestWord(arr) { | |
return arr | |
.map(getLength) | |
.reduce(findMax); | |
} | |
var arr = ['a', 'bbb', 'hellociao']; | |
findLongestWord(arr); |
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
// Create an increase(anArray, byNumber) function, that increases all the numbers in an array, by a given number. | |
// Non functional programming way | |
var sourceArray = [1, 2, 3]; | |
function increase(anArray, byNumber) { | |
for(var i=0; i<anArray.length; i++) { | |
anArray[i] += byNumber; | |
} | |
} | |
increase(sourceArray, 2); | |
console.log(sourceArray); // ?? | |
// Functional programming way | |
var sourceArray = [1, 2, 3]; | |
function increaseFP(anArray, byNumber) { | |
return anArray.map(function (number) { | |
return number + byNumber; | |
}); | |
} | |
var newArray = increaseFP(sourceArray, 2); | |
console.log(increaseFP(sourceArray, 2)); // ?? | |
console.log(sourceArray); // ?? | |
// Functional programming way (ES6) | |
var sourceArray = [1, 2, 3]; | |
function increaseFP(anArray, byNumber) { | |
return anArray.map(number => number + byNumber); | |
} | |
console.log(increaseFP(sourceArray, 2)); // ?? | |
console.log(sourceArray); // ?? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment