Skip to content

Instantly share code, notes, and snippets.

@imtrinity94
Created March 21, 2023 09:56
Show Gist options
  • Save imtrinity94/9cca4e04753435483ecb976d424771c3 to your computer and use it in GitHub Desktop.
Save imtrinity94/9cca4e04753435483ecb976d424771c3 to your computer and use it in GitHub Desktop.
The Y-combinator: a utility function
// The Y-combinator: a utility function!
var Y = function Y(hof) {
return function (x) {
return x(x);
}(function (x) {
return hof(function (y) {
return x(x)(y);
});
});
};
console.log([1, 2, 3, 4, 5].map(
// Wrap the higher-order function in the Y-combinator
// "factorial" is not a function's name: it's introduced as a parameter
Y(function (factorial) {
return function (n) {
return n <= 1 ? 1 : factorial(n - 1) * n;
};
})));
// [ 1, 2, 6, 24, 120 ]
@imtrinity94
Copy link
Author

Note: This method allocates a new closure for every iteration, which may significantly increase memory usage. It's only here to demonstrate the possibility, but should be avoided in production. Use a temporary variable or a named function expression instead.
https://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment