@algosail/logic
v0.1.0
Published
Logical connectives and boolean control-flow combinators.
Readme
@algosail/logic
Logical connectives and boolean control-flow combinators.
Contents
and
and :: Boolean -> Boolean -> BooleanLogical conjunction.
and(true)(true) // => true
and(true)(false) // => false
and(false)(false) // => falseor
or :: Boolean -> Boolean -> BooleanLogical disjunction.
or(false)(true) // => true
or(false)(false) // => false
or(true)(true) // => truenot
not :: Boolean -> BooleanLogical negation.
not(true) // => false
not(false) // => truecomplement
complement :: (a -> Boolean) -> a -> BooleanReturns a predicate that negates the original. Useful for building inverse filters.
const isEven = (x) => x % 2 === 0
const isOdd = complement(isEven)
isOdd(3) // => true
isOdd(4) // => false
[(1, 2, 3, 4)].filter(complement(isEven)) // => [1, 3]boolean_
boolean_ :: a -> a -> Boolean -> aCase analysis on a boolean — returns onFalse or onTrue.
boolean_('no')('yes')(true) // => 'yes'
boolean_('no')('yes')(false) // => 'no'
boolean_(0)(1)(true) // => 1ifElse
ifElse :: (a -> Boolean) -> (a -> b) -> (a -> b) -> a -> bApplies f if the predicate holds, g otherwise. Both branches receive the original value.
ifElse((x) => x > 0)((x) => x)((x) => -x)(-3) // => 3 (abs)
ifElse((x) => x > 0)((x) => x)((x) => -x)(5) // => 5
ifElse(Array.isArray)((arr) => arr.length)((s) => s.length)([1, 2, 3]) // => 3
ifElse(Array.isArray)((arr) => arr.length)((s) => s.length)('hello') // => 5when
when :: (a -> Boolean) -> (a -> a) -> a -> aApplies f only when the predicate holds; returns the value unchanged otherwise.
when((x) => x < 0)((x) => 0)(-5) // => 0
when((x) => x < 0)((x) => 0)(5) // => 5
// Guard against empty strings
when((s) => s.length === 0)(() => 'default')('') // => 'default'
when((s) => s.length === 0)(() => 'default')('hi') // => 'hi'unless
unless :: (a -> Boolean) -> (a -> a) -> a -> aApplies f only when the predicate does not hold. The inverse of when.
unless((x) => x > 0)((x) => -x)(-3) // => 3 (negated because not positive)
unless((x) => x > 0)((x) => -x)(5) // => 5 (left unchanged)
// Ensure string is trimmed unless it's already clean
unless((s) => s === s.trim())((s) => s.trim())(' hi ') // => 'hi'