Skip to content

Instantly share code, notes, and snippets.

@nicolo-ribaudo
Last active September 30, 2015 14:36
Show Gist options
  • Save nicolo-ribaudo/b8dc59878e48cd6123cf to your computer and use it in GitHub Desktop.
Save nicolo-ribaudo/b8dc59878e48cd6123cf to your computer and use it in GitHub Desktop.
JS Y-combinator
const Y = a=>(a=>a(a))(b=>a((...a)=>b(b)(...a)));
// Usage
/*
* var result = Y((the function itself) => (...parameters) => {
* return result;
* })(...parameters);
*
*/
// Example
const gcd = Y(gcd => (n1, n2, ...ns) => {
if (n2) return gcd(n2, n1 % n2, ...ns);
return n1;
});
const lcm = Y(lcm => (n1, n2, ...ns) => {
if (n2) lcm(n1 * n2 / gcd(n1, n2), ...ns);
return n1;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment