Last active
January 10, 2024 07:19
-
-
Save divs1210/45c29cfe1e6daf0ec608b12dde10903a to your computer and use it in GitHub Desktop.
Async JS is Stackless
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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