Skip to content

Instantly share code, notes, and snippets.

@Willmo36
Created March 6, 2018 10:41
Show Gist options
  • Save Willmo36/e71d54fc2101981363a5393ababc0eb5 to your computer and use it in GitHub Desktop.
Save Willmo36/e71d54fc2101981363a5393ababc0eb5 to your computer and use it in GitHub Desktop.
sequence.ts (Maybe only atm)
import { Maybe } from "monet";
/**
* Turns Maybe<T>[] into Maybe<T[]>
* This is basically Ramda's sequence; http://ramdajs.com/docs/#sequence
* But their types don't let us use it *angryface*
* @param xs List of maybes
*/
export function sequence<T>(xs: Maybe<T>[]): Maybe<T[]> {
return xs.reduce<Maybe<T[]>>((acc, x) => {
//turn the Maybe<T> into a Maybe<(ts: T[]) => T[]>
//which, via a closure, adds T to the T[]
const append = x.map(x1 => (xs1: T[]) => [...xs1, x1]);
//apply (ap = apply) the contents our of Maybe<T[]> to the above function
return acc.ap(append);
}, Maybe.of([]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment