Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active September 14, 2018 06:45
Show Gist options
  • Save OliverJAsh/4cba2554cd7f511fb6782bfcfb03b11f to your computer and use it in GitHub Desktop.
Save OliverJAsh/4cba2554cd7f511fb6782bfcfb03b11f to your computer and use it in GitHub Desktop.
FP list combinators demo with fp-ts
tsc && node main.js
import { catOptions, array } from 'fp-ts/lib/Array';
import { sequence, traverse } from 'fp-ts/lib/Traversable';
import { Option, some, none, option } from 'fp-ts/lib/Option';
{
//
// catOptions
// <T>(options: Array<Option<T>>) => Option<T>
//
const nameMaybes = [some('foo'), some('bar'), none];
const names = catOptions(nameMaybes);
console.log({ names });
// { names: [ 'foo', 'bar' ] }
}
{
//
// sequenceOptions
// <T>(options: Array<Option<T>>) => Option<Array<T>>
//
const sequenceOptions = sequence(option, array);
const nameMaybes1 = [some('foo'), some('bar'), none];
const maybeNames1 = sequenceOptions(nameMaybes1);
console.log({ maybeNames1 });
// { maybeNames1: none }
const nameMaybes2 = [some('foo'), some('bar'), some('baz')];
const maybeNames2 = sequenceOptions(nameMaybes2);
console.log({ maybeNames2 });
// { maybeNames2: some(["foo", "bar", "baz"]) }
}
type Person = { name: Option<string> };
const people1 = [{ name: some('foo') }, { name: some('bar') }, { name: none }];
const people2 = [
{ name: some('foo') },
{ name: some('bar') },
{ name: some('baz') },
];
const getName = (person: Person) => person.name;
{
//
// traverseOptions
// <A, B>(as: Array<A>, transform: (a: A) => Option<B>) => Option<Array<B>>
//
const traverseOptions = traverse(option, array);
const maybeNames1 = traverseOptions(people1, getName);
console.log({ maybeNames1 });
// { maybeNames1: none }
const maybeNames2 = traverseOptions(people2, getName);
console.log({ maybeNames2 });
// { maybeNames2: some(["foo", "bar", "baz"]) }
}
{
//
// filterMap
// <A, B>(as: Array<A>, transform: (a: A) => Option<B>) => Array<B>
//
const names = array.filterMap(people1, getName);
console.log({ names });
// { names: [ 'foo', 'bar' ] }
}
{
"dependencies": {
"fp-ts": "^1.8.0",
"typescript": "^3.0.3"
}
}
{
"compilerOptions": {
"strict": true
},
"files": [
"./main.ts"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment