Skip to content

Instantly share code, notes, and snippets.

@raineorshine
Created November 11, 2020 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raineorshine/a1da6806cc4e4f31b6f0ca8235090d8c to your computer and use it in GitHub Desktop.
Save raineorshine/a1da6806cc4e4f31b6f0ca8235090d8c to your computer and use it in GitHub Desktop.
Functional programming "or" in Javascript
/*
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