Getting Started With Functional Programming
Doubling an Array of Numbers
function doubleValues(arr) {
var newArr = []
for(var i = 0; i < arr.length; i++) {
newArr.push(arr[i] * 2)
}
return newArr
}
/*
calling doubleValues([1, 2, 3, 4])
gets us [ 2, 4, 6, 8 ]
*/
Filtering Out Odd Numbers
function evenValues(arr) {
var newArr = []
for(var i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
newArr.push(arr[i])
}
}
return newArr
}
/*
calling evenValues([1, 2, 3, 4])
gets us [ 2, 4 ]
*/
A Sum of a List of Numbers
function sumValues(arr) {
var sum = 0
for(var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum
}
/*
calling sumValues([1, 2, 3, 4])
gets us 10
*/
First Class Functions
function someFunction() {
return 'this is from some function'
}
/*
calling someFunction()
gets us 'this is from some function'
*/
First Class Functions
const theSameFunction = someFunction
/*
calling theSameFunction()
gets us 'this is from some function'
*/
First Class Functions
function callFunction(f) {
return f()
}
/*
calling callFunction(someFunction)
gets us 'this is from some function'
*/
Doubling an Array of Numbers
function doubleValues(arr) {
return arr.map(function (x) {
return 2 * x
})
}
/*
calling doubleValues([1, 2, 3, 4])
gets us [ 2, 4, 6, 8 ]
*/
Filtering Out Odd Numbers
function evenValues(arr) {
return arr.filter(function (x) {
return x % 2 === 0 }
)
}
/*
calling evenValues([1, 2, 3, 4])
gets us [ 2, 4 ]
*/
A Sum of a List of Numbers
function sumValues(arr) {
return arr.reduce(function (sum, x) {
return sum + x
})
}
/*
calling sumValues([1, 2, 3, 4])
gets us 10
*/
Arrow Functions
const add = (x, y) => x + y
const double_num = x => 2 * x
//by rights should be a one-liner
//but just to show you another way...
const triple_add = (x, y, z) => {
return 3 * (x + y + z)
}
/*
add(1, 2) gets us 3
double_num(5) gets us 10
triple_add(1, 2, 3) gets us 18
*/
functional-programming-getting-started-2
By Steve Smith
functional-programming-getting-started-2
- 488