Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/hojberg/sums-up
SumTypes in TypeScript
https://github.com/hojberg/sums-up
adt fp functional-programming javascript typescript
Last synced: 3 months ago
JSON representation
SumTypes in TypeScript
- Host: GitHub
- URL: https://github.com/hojberg/sums-up
- Owner: hojberg
- Created: 2018-09-03T21:26:37.000Z (over 6 years ago)
- Default Branch: main
- Last Pushed: 2023-01-05T10:13:59.000Z (about 2 years ago)
- Last Synced: 2024-04-13T16:20:36.942Z (9 months ago)
- Topics: adt, fp, functional-programming, javascript, typescript
- Language: TypeScript
- Size: 951 KB
- Stars: 28
- Watchers: 3
- Forks: 2
- Open Issues: 10
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
👍 Sums Up
===### Installation
```
npm install sums-up
```### Example
In TypeScript:
```typescript
import SumType from 'sums-up';class Maybe extends SumType<{ Just: [T]; Nothing: [] }> {}
function Just(value: T): Maybe {
return new Maybe("Just", value);
}function Nothing(): Maybe {
return new Maybe("Nothing");
}const x = Just("foo");
const result = x.caseOf({
Nothing: () => "nope",
Just: (a) => a + "bar",
});
```Or in JavaScript
```javascript
import SumType from 'sums-up';class Maybe extends SumType {}
function Just(value) {
return new Maybe("Just", value);
}function Nothing() {
return new Maybe("Nothing");
}const x = Just("foo");
const result = x.caseOf({
Nothing: () => "nope",
Just: (a) => a + "bar",
});
```### Wildcard Matching
If the kind of a sum type instance isn't present in the pattern given to `caseOf`, a default key called `_` will be used instead.
```ts
import SumType from 'sums-up';class RequestState extends SumType<{
NotStarted: [];
Connecting: [];
Downloading: [number];
Completed: [T];
Failed: [string];
}> {}const state = new RequestState('Failed', 'Connection reset.');
const progressPercentage = state.caseOf({
Downloading: pct => pct,
Completed: () => 100,
_: () => 0
});
```Contributors:
@hojberg @dfreeman @AdamEdgett