Last active
October 10, 2022 04:23
-
-
Save rajatk16/331c7da3e3614f96b4538ca8eebdeb7d to your computer and use it in GitHub Desktop.
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
| queueCreator = () => { | |
| const queue = [] | |
| return { | |
| add(x) { | |
| queue.unshift(x) | |
| }, | |
| remove() { | |
| if (queue.length === 0) { | |
| return undefined | |
| } | |
| return queue.pop() | |
| }, | |
| next() { | |
| if (queue.length === 0) { | |
| return undefined | |
| } | |
| return queue[queue.length - 1] | |
| }, | |
| get length() { | |
| return queue.length | |
| }, | |
| empty() { | |
| return queue.length === 0 | |
| } | |
| } | |
| } | |
| nodeCreator = (id) => { | |
| const neighbors = [] | |
| return { | |
| id, | |
| neighbors, | |
| addNeighbors(node) { | |
| neighbors.push(node) | |
| } | |
| } | |
| } | |
| graphCreator = (uni = false) => { | |
| const nodes = [] | |
| const edges = [] | |
| return { | |
| uni, | |
| nodes, | |
| edges, | |
| addNode(id) { | |
| nodes.push(nodeCreator(id)) | |
| }, | |
| searchNode(id) { | |
| return nodes.find(n => n.id === id) | |
| }, | |
| addEdge(idOne, idTwo) { | |
| const a = this.searchNode(idOne) | |
| const b = this.searchNode(idTwo) | |
| a.addNeighbors(b) | |
| if (!uni) { | |
| b.addNeighbors(a) | |
| } | |
| edges.push(`${idOne}${idTwo}`) | |
| }, | |
| display() { | |
| return nodes.map(({neighbors, id}) => { | |
| let output = `${id}` | |
| if (neighbors.length) { | |
| output += ` => ${neighbors.map(node => node.id).join(' ')}` | |
| } | |
| return output | |
| }).joing('\n') | |
| }, | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment