Skip to content

Instantly share code, notes, and snippets.

@ion1
Last active February 11, 2024 15:36
Show Gist options
  • Save ion1/b030109cd799add64742acc35982bc7a to your computer and use it in GitHub Desktop.
Save ion1/b030109cd799add64742acc35982bc7a to your computer and use it in GitHub Desktop.
Testing JavaScript Promise monad laws
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