Last active
February 11, 2024 15:36
-
-
Save ion1/b030109cd799add64742acc35982bc7a to your computer and use it in GitHub Desktop.
Testing JavaScript Promise monad laws
This file contains 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
await (async () => { | |
function wrap(p) { | |
return p.then( | |
(res) => ["ok", res], | |
(err) => ["error", err] | |
); | |
} | |
async function compare(title, pa, pb) { | |
const a = await wrap(pa); | |
const b = await wrap(pb); | |
console.info(title, { a, b }); | |
} | |
async function leftIdentity(f, x) { | |
await compare("left identity", f(x), Promise.resolve(x).then(f)); | |
} | |
async function rightIdentity(p) { | |
await compare( | |
"right identity", | |
p, | |
p.then((x) => Promise.resolve(x)) | |
); | |
} | |
async function associativity(p, f, g) { | |
await compare( | |
"associativity", | |
p.then(f).then(g), | |
p.then((x) => f(x).then(g)) | |
); | |
} | |
await leftIdentity((x) => Promise.resolve(x), "foo"); | |
await leftIdentity((x) => Promise.reject("foo err"), "foo"); | |
await rightIdentity(Promise.resolve("bar")); | |
await rightIdentity(Promise.reject("bar err")); | |
await associativity( | |
Promise.resolve("baz"), | |
(x) => Promise.resolve(x), | |
(x) => Promise.resolve(x) | |
); | |
await associativity( | |
Promise.reject("baz err 1"), | |
(x) => Promise.resolve(x), | |
(x) => Promise.resolve(x) | |
); | |
await associativity( | |
Promise.resolve("baz"), | |
(x) => Promise.reject("baz err 2"), | |
(x) => Promise.resolve(x) | |
); | |
await associativity( | |
Promise.resolve("baz"), | |
(x) => { | |
throw "baz throw 2"; | |
}, | |
(x) => Promise.resolve(x) | |
); | |
await associativity( | |
Promise.resolve("baz"), | |
(x) => Promise.resolve(x), | |
(x) => Promise.reject("baz err 3") | |
); | |
await associativity( | |
Promise.resolve("baz"), | |
(x) => Promise.resolve(x), | |
(x) => { | |
throw "baz throw 3"; | |
} | |
); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment