Skip to content

Instantly share code, notes, and snippets.

@Nymphium
Last active July 20, 2019 21:41
Show Gist options
  • Save Nymphium/57bad27edf4031f20db9739ddd0be614 to your computer and use it in GitHub Desktop.
Save Nymphium/57bad27edf4031f20db9739ddd0be614 to your computer and use it in GitHub Desktop.
import { isNone, Option, none, some } from 'fp-ts/lib/Option';
function runOption<T>(th: () => Iterator<Option<T>, Option<T>, unknown>): Option<T> {
const iter = th();
const go = (
{ done, value: v }: IteratorResult<Option<T>, Option<T>>,
): Option<T> => (done || isNone(v) ? v : go(iter.next(v.value)));
return go(iter.next());
}
function* th() {
/*
option.chain(some(3), x =>
option.chain(some(5), y =>
some(x + y)))
*/
const x = yield some(3);
const y = yield some(5);
return some(x + y);
}
function* th2() {
const x = yield some(7);
yield none;
return some(x + 5);
}
console.log(runOption(th)); // { _tag: 'Some', value: 17 }
console.log(runOption(th2)); // { _tag: 'None' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment