Skip to content

Instantly share code, notes, and snippets.

@bhuizi
Last active June 5, 2018 03:55
Show Gist options
  • Save bhuizi/3555f794a4c7148f331f3bc4b1981694 to your computer and use it in GitHub Desktop.
Save bhuizi/3555f794a4c7148f331f3bc4b1981694 to your computer and use it in GitHub Desktop.
functional-lite
// compose
sum = (x, y) => x + y;
mult = (x, y) => x * y;
const result = sum(mult(3, 4), 5);
console.log(result);
compose2 = (fn1, fn2) => {
return function comp() {
let args = [].slice.call(arguments);
return fn2(
fn1(args.shift(), args.shift()),
args.shift()
);
}
}
const multAndSum = compose2(mult, sum);
const result2 = multAndSum(3, 4, 5);
console.log(result2);
//closure
const nums = [2, 3, 4];
doubleThemImmutable = (v) => v * 2;
const doubled = nums.map(doubleThemImmutable);
console.log(doubled);
addUp = (x, y) => {
return (y) => x + y;
}
const nextStep = add10(10);
const result3 = nextStep(20);
seven = (x, y) => x + y;
let x = seven(3, 4);
//recursion
sumRecur = (...args) => {
if(args.length <= 2) {
return args[0] + args[1];
}
return (args[0] + sumRecur(...args.slice(1)))
}
const result4 = sumRecur(3, 4, 5);
mult = (...args) => {
if(args.length <= 2) {
return args[0] * args[1];
}
return(
args[0] * mult(...args.slice(1))
)
}
const result5 = mult(2, 4, 5, 6, 7, 8);
// composition examples
foo = (x) => () => x;
add = (x, y) => x + y;
add2 = (fn1, fn2) => add(fn1(), fn2())
const result = add2(foo(42), foo(10));
console.log(result);
//recursive
foo = (x) => () => x;
add = (x, y) => x + y;
add2 = (fn1, fn2) => add(fn1(), fn2())
const fns = [foo(10), foo(42), foo(12)]
addn = (...args) => {
if(args.length <= 2) {
return add2(args[0], args[1]);
}
return add2(args[0], foo(addN(...args.slice(1))));
}
const result2 = addn(foo(42), foo(10), foo(10));
console.log(result2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment