@universal-apps/ts-utils
v1.1.3
Published
A Typescript utility library with some utility functions to level up your dev ex using functional programming
Downloads
2
Maintainers
Readme
ts-utils
A typescript utility library to help utilize functional programming concepts by re-creating monads like Option (Scala), Either (Scala) and Result (Rust) in Typescript.
Check out the blog post for a good overview.
Installation
npm i @universal-apps/ts-utils
# OR
pnpm i @universal-apps/ts-utils
Library
Usage & Examples
// Option
const someValue: Option<number> = some(42) // { value: 42 }
const noValue: Option<number> = none() // {}
// Utilities to match on the Option type
matchOptionF({
some: (value) => value,
none: () => undefined,
})(someValue)
// Either
const rightFn = (): Either<Error, number> => right(42) // { value: 42 }
const leftFn = (): Either<Error, number> => left(new Error('bad')) // { error: Error('bad) }
// Utilities to match on the Either type
matchEitherF<Error, number, Error, number>({
right: (result) => result,
left: (err) => err,
})(rightFn)
// Result
const okFn = (): Result<number, Error> => ok(42) // { value: 42 }
const errFn = (): Result<number, Error> => err(new Error('bad')) // { error: Error('bad') }
// Utilities to match on the Result type
matchResultF({
ok: (result) => result,
err: (err) => err,
})(okFn())
// OR
matchResultF<number, Error, number, Error>({
ok: (result) => result,
err: (err) => err,
})(okFn())
// Result Tuple
const result: ResultT<number> = 42 // 1
const error: ErrorT = new Error('bad') // Error('bad')
const resultTuple: ResultTuple<number> = toTuple({ result }) // [42, undefined]
// OR
const resultTuple: ResultTuple<number> = toTuple({ error }) // [undefined, new Error('bad')]
// Say goodbye to try/catch and use it this way
const aPromise = async (): Promise<ResultTuple<number>> =>
Promise.resolve(toTuple({ result: 42 }))
const fn = async (): Promise<any> => {
const [result, error] = await aPromise()
if (error) {
// do something with error
throw error
} else {
// do something with result
console.log(`Result is ${result}`)
}
}
More examples can be found here
Tests
The tests can be found here
pnpm run test
# or
pnpm run test:ui
Inspiration
Inspired by this article by Dan Imhoff.
Resources
fp-ts library
EffectTS library
Functional Programming Series on Youtube
Publishing
pnpm version <major|minor|patch>
pnpm publish --dry-run --publish-branch <current-branch>
pnpm publish