Skip to content

Instantly share code, notes, and snippets.

@alexcanessa
Created June 20, 2016 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexcanessa/988036c04f48a7cc2cc05824990bf4cd to your computer and use it in GitHub Desktop.
Save alexcanessa/988036c04f48a7cc2cc05824990bf4cd to your computer and use it in GitHub Desktop.
Functional programming snippets
// 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);
// 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