Skip to content

Instantly share code, notes, and snippets.

@fhpriamo
Last active October 7, 2020 17:29
Show Gist options
  • Save fhpriamo/ac4d3890d94b44f8ca7d0ccc080450a2 to your computer and use it in GitHub Desktop.
Save fhpriamo/ac4d3890d94b44f8ca7d0ccc080450a2 to your computer and use it in GitHub Desktop.
Tests for basic composition properties in JS (with Jest)
function compose (...fns) {
function _compose(fnA, fnB) {
if (fnA === undefined) {
throw new Error('compose needs at least one argument')
}
return (...args) => {
return fnA(fnB(...args));
}
}
return fns.reduce((acc, cur) => {
return _compose(acc, cur)
});
}
function id(x) {
return x;
};
function square(n) {
return n * n;
}
// f :: A -> B
// g :: B -> C
// h :: C -> D
// h . (g . f) = (h . g) . f = h . g . f
test('β„Ž ∘ (𝑔 ∘ 𝑓 ) = (β„Ž ∘ 𝑔) ∘ 𝑓 = β„Ž ∘ 𝑔 ∘ 𝑓', () => {
const c = compose;
const h = (x) => `h(${x})`;
const g = (x) => `g(${x})`;
const f = (x) => `f(${x})`;
const r = c(h, c(g, f))
const s = c(c(h, g), f)
const t = c(h, g, f);
const EXPECTED = 'h(g(f(7)))';
expect(r(7)).toBe(EXPECTED);
expect(s(7)).toBe(EXPECTED);
expect(t(7)).toBe(EXPECTED);
});
// id . f = f
test('id𝐡 ∘ 𝑓 = 𝑓', () => {
const r = compose(id, square);
expect(r(4)).toBe(16);
});
// f . id = f
test('𝑓 ∘ id𝐴 = 𝑓', () => {
const r = compose(square, id);
expect(r(9)).toBe(81);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment