Created
March 6, 2018 10:41
-
-
Save Willmo36/e71d54fc2101981363a5393ababc0eb5 to your computer and use it in GitHub Desktop.
sequence.ts (Maybe only atm)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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