Skip to content

Instantly share code, notes, and snippets.

@turboMaCk
Last active November 16, 2016 00:22
Show Gist options
  • Save turboMaCk/2d415f17a572097fd4f740f30bce2dec to your computer and use it in GitHub Desktop.
Save turboMaCk/2d415f17a572097fd4f740f30bce2dec to your computer and use it in GitHub Desktop.
Currying vs partial application vs factory
/**
Example is using Heron's formula for calculating area of triangle
more info: https://en.wikipedia.org/wiki/Heron%27s_formula
*/
// Given a function of type f: (X x Y x Z) -> N,
// currying produces f: X -> (Y -> (Z -> N))
// Num -> (Num -> (Num -> Num))
function triangleArea(a) {
return function(b) {
return function(c) {
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
};
};
}
// Num -> (Num -> Num)
const withAequal5 = triangleArea(5);
withAequal5(3)(3);
// => 4.14578098794425
withAequal5(4)(2);
// => 3.799671038392666
/**
Example is using Heron's formula for calculating area of triangle
more info: https://en.wikipedia.org/wiki/Heron%27s_formula
*/
// Given (X x Y x Z),
// factory THIS produces f: () -> N
function triangleArea(a, b, c) {
return function() {
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
};
}
// () -> N
const triangle = triangleArea(5, 3, 3);
const triangle2 = triangleArea(5, 4, 2);
triangle();
// => 4.14578098794425
triangle2();
// => 3.799671038392666
/**
Example is using Heron's formula for calculating area of triangle
more info: https://en.wikipedia.org/wiki/Heron%27s_formula
*/
// Given a function of type f: (X x Y x Z) -> N,
// fixingbinding produces fpartial: (Y x Z) -> N
function triangleArea(a, b, c) {
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
// (X x Y) -> N
const partial = triangleArea.bind(undefined, 5);
partial(3, 3);
// => 4.14578098794425
partial(4, 2);
// => 3.799671038392666
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment