Created
November 11, 2020 19:25
-
-
Save raineorshine/a1da6806cc4e4f31b6f0ca8235090d8c to your computer and use it in GitHub Desktop.
Functional programming "or" in Javascript
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
/* | |
An "or" function is a higher-order function that composes multiple predicates into one, | |
such that the composed predicate will return true if at least one of the predicates | |
returns true for the given argument. (A predicate is a function that returns `boolean`.) | |
e.g. | |
const isEven = n => n%2 === 0 | |
const isPositive = n => n > 0 | |
// un-fancy | |
items.filter(x => isEven(x) || isPositive(x)) | |
// fancy | |
items.filter(or(isEven, isPositive)) | |
*/ | |
// simple | |
let or = (f, g) => x => f(x) || g(x) | |
// variable args | |
let or = (f, g) => (...args) => f(...args) || g(...args) | |
// variable predicates, variable args | |
or = (...fs) => (...args) => | |
fs.length > 0 && ( | |
fs[0](...args) || | |
or(fs.slice(1))(...args) | |
) | |
/* | |
Libraries: | |
- https://landau.github.io/predicate/#or | |
- https://github.com/Moeriki/node-fp-or | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment