Catling 🔫🐈
A monad library in TypeScript
Use monads in your code for functional programming joy.
Catling is influenced by the Scala standard library and Cats
Installation
Install using yarn or npm
yarn:
yarn add catling
npm:
npm install catling --save
API
Option
An option is a great way to represent a value which may or may not exist. An option is either a Some
or a None
.
.maptrim .filtern.length !== 0 .mapn.toUpperCase console.logupper // either "Some("JIMMY")" or "None"
map
Applies the function given to the value if it's a Some, otherwise return None.
// Some(20)
flatMap
Applies the function that maps the value in the Option to a new Option.
.flatMapOptionperson.age // Some(20) or None
filter
Returns the Option if the predicate returns true, otherwise return a None.
fold / chain
Applies the first function if the Option is a None, else applies the second function.
// 'JIMMY'
get
Returns the value of the Option if it's a Some, otherwise return undefined
// 'Jimmy'
getOrElse
Returns the value of the Option if it's a Some, otherwise return the alternative.
// 'Bob'
toArray
Returns an array containing the inner value if it's a Some, or an empty array if it's None.
None.toArray // []Some'Bob'.toArray // ['Bob']
toList
Returns a List containing the inner value if it's a Some, or an empty List if it's None.
None.toList // List()Some'Bob'.toList // List('Bob')
Either
An either represents a value consisting of one of two possible types. It's typically used to represent the result of something that may fail. Eithers are right-biased.
.mapn + 20 console.logmyNum1 // "Right(22)" .mapn + 20 console.logmyNum2 // "Left("Cannot divide by zero")"
toArray
Returns an array containing the inner value if it's a Right, or an empty array if it's Left.
Left'fail'.toArray // []Right'success'.toArray // ['success']
toList
Returns a List containing the inner value if it's a Right, or an empty List if it's Left.
Left'fail'.toList // List()Right'success'.toList // List('success')
Immutable List
An immutable list behaves much like the native array, expect it cannot be mutated.
.mapdouble .filtergreaterThan3 .fold0, add console.logresult // 22
Writer
A Writer is a context that carries with it some sort of log with its computation.
.flatMapWriterList'adding 5', val + 5 .flatMapWriterList'doubling', val * 2 console.logmyWriter // Writer(List(initial value, adding 5, doubling), 30)
The log part of the writer must be a semigroup according to the fantasy-land spec, meaning it must have a concat
method. This is used to combine the logs from the source writer.
Reader
A Reader allows injecting dependencies into your functions. It delays execution until the Reader is run with the desired configuration.
connect'session'.run // POST http://example.com:8000/session