Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/janstuemmel/yep

Easy functional programming with Typescript
https://github.com/janstuemmel/yep

category-theory fp functional-programming futures javascript promises typescript

Last synced: 15 days ago
JSON representation

Easy functional programming with Typescript

Awesome Lists containing this project

README

        

# yep

A functional programming library that treats every result as promise
and therefor doesn't differentiate between async and sync code.

The code should showcase that fp is not hard in typecript.

Please look at examples and tests.

## Usage

```ts
import {type Box, all, flat, map, nah, or, pipe, tap, yep} from './lib.js';

class HttpError extends Error {}
class ParseError extends Error {}

const req = (url: string): Box =>
fetch(url)
.then(yep)
.catch(() => nah(new HttpError('http error')));

const parse = (res: Response): Box =>
res
.json()
.then((json) => yep(json as T))
.catch(() => nah(new ParseError('json parse error')));

const checkStatus = (res: Response) =>
res.status >= 400 ? nah(new HttpError('status error')) : yep(res);

const getPokemon = (name: string) =>
pipe(
yep(`https://pokeapi.co/api/v2/pokemon/${name}`),
flat(req),
tap((res) => console.log(`Requested ${name} with response status ${res.status}`)),
flat(checkStatus),
flat(parse<{weight: number; name: string}>),
);

const program = pipe(
yep(['ditto', 'onix']),
flat((names) => all(names.map(getPokemon))),
map(([v, w]) =>
v.weight < w.weight
? `${w.name} heavier then ${v.name}`
: `${v.name} heavier then ${w.name}`,
),
or((e) => yep(`recovered err: ${e.message}`)),
);

program.then(console.log);
```