Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/oakfang/adt
https://github.com/oakfang/adt
Last synced: 20 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/oakfang/adt
- Owner: oakfang
- Created: 2024-05-04T19:26:44.000Z (9 months ago)
- Default Branch: main
- Last Pushed: 2024-05-14T20:07:59.000Z (9 months ago)
- Last Synced: 2024-11-09T18:19:13.853Z (3 months ago)
- Language: TypeScript
- Size: 41 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Algebraic Data Types for typescript
This is a somewhat naive implementation of ADTs for typescript.
## `option` - the "maybe" type module
### Main Exports
- `none(): None` create an instance of `Option` that holds no value (unit type)
- `some(value: T): Some` create an instance of `Option` that holds a value
- `type Option = None | Option`### Utilities
- `isNone(value)` - is provided argument of type `None`
- `getOrElse(option: Option, default: T): T` - get an optional value if exists, fallback to default otherwise
- `fromNullable(value: T | null | undefined): Option` create an `Option` from a possibly nullable value, where nullish become `None` and other values become `Some`### Example Usage
Let's say we have a sparse array of numbers. We'd like to sum it, but some members of the array might be nullish. We can't use falsy values as indication (because 0), so let's try to use options instead.
```ts
import { option } from "@oakfang/adt";const numbers: Array = [
/*...*/
];
const sum = numbers
// Array -> Array>
.map(fromNullable)
// Array> -> number[]
.map((o) => getOrElse(o, 0))
// number[] -> number
.reduce((x, y) => x + y, 0);
```## `Result` - the "computation that might fail" type
Some function might throw, but the issue with that is that neither JS nor TS provide us with a way to account for these thrown errors in a type-safe manner. The `Result` type aims to remove the need for thrown exception, as it encapsulates both a function that follows the "happy flow" (i.e., returns) and one that doesn't.