Created
August 17, 2016 11:08
-
-
Save ktsn/4c7e5bb791a5bb957ce7c1a159e64ceb to your computer and use it in GitHub Desktop.
This file contains 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
export function traverse<T, U>(obj: Dictionary<T>, f: (t: T) => Array<U>) : Array<Dictionary<U>> { | |
return sequence( | |
mapValues(obj, t => { | |
return f(t) | |
}) | |
) | |
} | |
export function sequence<T>(obj: Dictionary<Array<T>>) : Array<Dictionary<T>> { | |
function loop<T>(acc: Array<Dictionary<T>>, obj: Dictionary<Array<T>>) : Array<Dictionary<T>> { | |
return traverseHead(obj) | |
.map(head => loop(acc.concat(head), traverseTail(obj))) | |
.orElse(acc) | |
} | |
return loop([], obj) | |
} | |
export function traverseHead<T>(obj: Dictionary<Array<T>>) : Maybe<Dictionary<T>> { | |
const res: Dictionary<T> = {} | |
forEach(obj, (val: T[], key: string) => { | |
maybe(val[0]).forEach(val => { | |
res[key] = val | |
}) | |
}) | |
if (Object.keys(res).length > 0) { | |
return maybe(res) | |
} else { | |
return maybe<Dictionary<T>>(null) | |
} | |
} | |
export function traverseTail<T>(obj: Dictionary<Array<T>>) : Dictionary<Array<T>> { | |
return mapValues(obj, (val: T[]) => { | |
return val.slice(1) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment