Skip to content

Instantly share code, notes, and snippets.

@kasperpeulen
Last active November 18, 2020 11:08
Show Gist options
  • Save kasperpeulen/960f2a61453ef6b56922e4c5b8e9fbe9 to your computer and use it in GitHub Desktop.
Save kasperpeulen/960f2a61453ef6b56922e4c5b8e9fbe9 to your computer and use it in GitHub Desktop.
Monad laws for promise
test('left identity', async () => {
async function f(x: number) {
return 2 * x;
}
function g(x: number) {
return f(x).then(y => Promise.resolve(y));
}
const x = 2;
expect(await f(x)).toEqual(await g(x));
})
test('left identity async function', async () => {
async function f(x: number) {
return 2 * x;
}
async function g(x: number) {
const y = await f(x);
return await Promise.resolve(y);
}
const x = 2;
expect(await f(x)).toEqual(await g(x));
})
test('right identity', async () => {
async function f(x: number) {
return 2 * x;
}
function g(x: number) {
return Promise.resolve(x).then(f);
}
const x = 2;
expect(await f(x)).toEqual(await g(x));
})
test('right identity async function', async () => {
async function f(x: number) {
return 2 * x;
}
async function g(x: number) {
let _x = await Promise.resolve(x);
return await f(_x);
}
const x = 2;
expect(await f(x)).toEqual(await g(x));
})
test('Associativity', async () => {
async function f(x: number) {
return 2 * x;
}
async function g(x: number) {
return 3 * x;
}
async function h(x: number) {
return 4 * x;
}
function left(x: number) {
return f(x).then(g).then(h);
}
function right(x: number) {
return f(x).then((y) => g(y).then(h));
}
const x = 2;
expect(await left(x)).toEqual(await right(x));
});
test('Associativity async', async () => {
async function f(x: number) {
return 2 * x;
}
async function g(x: number) {
return 3 * x;
}
async function h(x: number) {
return 4 * x;
}
async function left(x: number) {
const y = await f(x);
const z = await g(y);
return await h(z);
}
async function right(x: number) {
const y = await f(x);
const z = await g(y);
return await h(z);
}
const x = 2;
expect(await left(x)).toEqual(await right(x));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment