Skip to content

Instantly share code, notes, and snippets.

@janmarsicek
Created September 30, 2017 19:48
Show Gist options
  • Save janmarsicek/fc8c20f171ab1b894cab674ae04ac7d6 to your computer and use it in GitHub Desktop.
Save janmarsicek/fc8c20f171ab1b894cab674ae04ac7d6 to your computer and use it in GitHub Desktop.
https://bethallchurch.github.io/JavaScript-and-Functional-Programming/
////////////////
var add = (x, y) => x + y
var square = (x) => x * x
var addThenSquare = (x, y) => square(add(x, y))
addThenSquare(5, 2)
////////////////
var composeTwo = (f, g) => (x, y) => g(f(x, y))
var addThenSquare = composeTwo(add, square)
addThenSquare(5, 2)
////////////////
var composeMany = (...args) => {
var funcs = args;
return (...args) => {
funcs.forEach(func => {
args = [func.apply(this, args)];
});
return args[0]
}
}
var addThenSquare = composeMany(add, square)
addThenSquare(5, 2)
////////////////
var multiply = (x, y) => x * y
var partApply = (fn, x) => (y) => fn(x, y)
var double = partApply(multiply, 2)
var triple = partApply(multiply, 3)
var quadruple = partApply(multiply, 4)
console.log(double(2))
console.log(triple(2))
console.log(quadruple(2))
////////////////
var multiply = (x, y) => x * y
var curry = fn => x => y => fn(x, y) // is a function that takes `fn` as an argument and returns function `x => y => fn(x, y)`
var curriedMultiply = curry(multiply) // is a function returned from `curry` that takes `x` as an argument and returns function `y => multiply(x, y)`
var double = curriedMultiply(2) // is a function returned from `curriedMultiply` that takes `y` as an argument and calls `multiply(2, y)`
console.log(double(3))
console.log(`is same as multiply(2, 3)`:, multiply(2, 3))
////////////////
var multiply = (x, y, z) => x * y * z
var curry = fn => x => y => z => fn(x, y, z)
var partApply = (fn, x) => (y, z) => fn(x, y, z)
var curriedMultiply = curry(multiply)
var partiallyAppliedMultiply = partApply(multiply, 10)
console.log(curriedMultiply(10)(5)(2));
console.log(partiallyAppliedMultiply(5, 2));
////////////////
var factorial = n => n === 0 ? 1 : n * factorial(n - 1)
console.log(factorial(10))
////////////////
var factorial = (n, base) => {
if (n === 0) {
return base;
}
base *= n;
return factorial(n - 1, base)
}
console.log(factorial(10, 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment