Skip to content

Instantly share code, notes, and snippets.

@i-am-tom
Last active October 5, 2016 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save i-am-tom/4c92bebd6f6561256fa0bd7baae42931 to your computer and use it in GitHub Desktop.
Save i-am-tom/4c92bebd6f6561256fa0bd7baae42931 to your computer and use it in GitHub Desktop.
Using flatMap to traverse graphs.
const Graph = {
A: ['B', 'C'],
B: ['D'],
C: ['A', 'B'],
D: ['E']
}
const nextSteps = node => Graph[node]
// Forgive me, padre
Array.prototype.flatMap = function (f) {
return this.map(f).reduce(
(xs, ys) => xs.concat(ys)
)
}
nextSteps('A') // [B, C]
.flatMap(nextSteps) // [D, A, B]
.flatMap(nextSteps) // [E, B, C, D]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment