Created
December 6, 2021 11:32
-
-
Save laalaguer/283613284ad9cdb7375dcf12d9bda272 to your computer and use it in GitHub Desktop.
Uniswap V2 route (path) finder for two tokens, if given a set of pools
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
class PathFinder { | |
constructor(pairs) { | |
this.graph = new Map() | |
pairs.forEach((item) => { | |
if (!this.graph.has(item[0])) { | |
this.graph.set(item[0], new Array()) | |
} | |
if (!this.graph.has(item[1])) { | |
this.graph.set(item[1], new Array()) | |
} | |
this.graph.get(item[0]).push(item[1]) | |
this.graph.get(item[1]).push(item[0]) | |
}) | |
} | |
find(a, b) { | |
this.start = a | |
this.target = b | |
this.visited = new Set() | |
return this.dfs(this.start) | |
} | |
dfs(s) { | |
const paths = new Array() | |
if (s === this.target) { | |
paths.push([s]) | |
return paths | |
} | |
if (this.visited.has(s)) { | |
return paths | |
} | |
this.visited.add(s) | |
this.graph.get(s).forEach((neighbour) => { | |
this.dfs(neighbour).forEach((path) => { | |
paths.push([s, ...path]) | |
}) | |
}) | |
this.visited.delete(s) | |
return paths | |
} | |
} | |
const pairs = [['a', 'b'], ['a', 'c'], ['b', 'd'], ['c', 'd']] | |
const pf = new PathFinder(pairs) | |
console.log(pf.find('b', 'd')) | |
console.log(pf.find('a', 'b')) | |
console.log(pf.find('a', 'd')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment