Skip to content

Instantly share code, notes, and snippets.

@lubien
Last active January 7, 2020 00:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lubien/ca26915fd2a169f35509191468fb7f33 to your computer and use it in GitHub Desktop.
Save lubien/ca26915fd2a169f35509191468fb7f33 to your computer and use it in GitHub Desktop.
Cond

Create a cond function that takes 2 arguments:

  1. An matrix in the format:
[
  [firstCondition, firstCallback],
  [secondCondition, secondCallback],
  ...
]
  1. Any value.

So that the functions works as:

  1. If firstCondition(value) is true, return firstCallback(value).
  2. If secondCondition(value) is true, return secondCallback(value).
  3. ...
  4. If nthCondition(value) is true, return nthCallback(value).
  5. Throw if no condition is true.

Example:

const x = 10

cond([
  [greaterThan10, half],
  [equals10, double],
  [lowerThan10, triple]
], x)

// returns double(10)
const double = x => x * 2
const half = x => x / 2
const id = x => x
const T = () => true
const gt = n => x => x > n
const lt = n => x => x < n
const cond = (conds, x) => {
const [, f] = conds.find(([pred, f]) => pred(x))
return f(x)
}
console.log(
cond(
[ [gt(10), half]
, [lt(10), double]
, [T, id]
], 10)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment