Skip to content

Instantly share code, notes, and snippets.

@divs1210
Last active January 10, 2024 07:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divs1210/45c29cfe1e6daf0ec608b12dde10903a to your computer and use it in GitHub Desktop.
Save divs1210/45c29cfe1e6daf0ec608b12dde10903a to your computer and use it in GitHub Desktop.
Async JS is Stackless
// StackGC
// =======
const StackGC = async () => null;
// Tests
// =====
// util
function assert(assertion, msg) {
console.assert(assertion, `%s`, msg);
}
// 1. Simple recursion
// ===================
// recursive factorial
async function fact(n) {
n = BigInt(n);
if (n < 2)
return 1n;
await StackGC();
return n * await fact(n - 1n);
}
// non-recursive factorial
function fact2(n) {
n = BigInt(n);
let f = 1n;
while(n > 1)
f *= n--;
return f;
}
assert(
await fact(10000) === fact2(10000),
`fact(10000)`
);
// 2. Mutual recursion
// ===================
async function isEven(x) {
if (x === 0)
return true;
await StackGC();
return await isOdd(x - 1);
}
async function isOdd(x) {
if (x === 0)
return false;
await StackGC();
return await isEven(x - 1);
}
assert(
await isEven(20000) === true,
`isEven(20000)`
);
assert(
await isOdd(20001) === true,
`isOdd(20001)`
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment