Last active
October 7, 2020 17:29
-
-
Save fhpriamo/ac4d3890d94b44f8ca7d0ccc080450a2 to your computer and use it in GitHub Desktop.
Tests for basic composition properties in JS (with Jest)
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
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