@zcabjro/either v0.9.0
@zcabjro/either
Summary
Represents values that can be one of two possible types.
Instances of Either are either a Left or a Right.
Inspired by Scala's Either type.
Installation
npm install @zcabjro/eitherExamples
value
Gets the underlying value from either Left or Right.
left("Alice").value // "Alice"
right("Bob").value // "Bob"getOrElse
Returns the underlying value from Right or the given fallback for Left.
left("Alice").getOrElse("Bob") // "Bob"
right("Bob").getOrElse("Alice") // "Bob"getOrElseLazy
Returns the underlying value from Right or the result of the given function for Left.
left("Alice").getOrElseLazy(() => "Bob") // "Bob"
right("Bob").getOrElseLazy(() => "Alice") // "Bob"getOrElseThrow
Returns the underlying value from Right or throws for Left. You may pass a function to control what gets thrown.
left("Alice").getOrElseThrow() // throw "Alice"
left("Alice").getOrElseThrow(a => new Error(a)) // throw new Error("Alice")
right("Bob").getOrElseThrow() // "Bob"
right("Bob").getOrElseThrow(a => new Error(a)) // "Bob"isLeft
Returns true for Left and false for Right.
left("Alice").isLeft // true
right("Bob").isLeft // falseisRight
Returns true for Right and false for Left.
left("Alice").isRight // false
right("Bob").isRight // truemap
Applies the given function to a Right. Does nothing to a Left.
left("Alice").map(s => s.length) // Left("Alice")
right("Alice").map(s => s.length) // Right(5)flatMap
Similar to map except that the function passed to flatMap must return an Either. Calling flatMap on a Right will return the result of the given function. Does nothing to a Left.
left("Alice").flatMap(() => left(0)) // Left("Alice")
left("Alice").flatMap(() => right(1)) // Left("Alice")
right("Alice").flatMap(() => left(0)) // Left(0)
right("Alice").flatMap(() => right(1)) // Right(1)fold
Receives two functions. The first is applied to a Left while the second is applied to a Right.
left("Alice").fold(() => 0, () => 1) // 0
right("Alice").fold(() => 0, () => 1) // 1swap
Swap so that a Left becomes a Right or vice versa.
left("Alice").swap(); // Right("Alice")
right("Alice").swap(); // Left("Alice")