(str: string)
| 18 | } |
| 19 | |
| 20 | static parse(str: string): Digraph { |
| 21 | const lines = str.split('\n'); |
| 22 | const graph = new Digraph(); |
| 23 | |
| 24 | let index = 0; |
| 25 | for (const line of lines) { |
| 26 | const trimmedLine = line.trim(); |
| 27 | if (trimmedLine.startsWith('digraph ')) { |
| 28 | if (index !== 0) { |
| 29 | this.throwInvalidGraph(); |
| 30 | } |
| 31 | } else if (trimmedLine === '}') { |
| 32 | if (index !== lines.length - 1) { |
| 33 | this.throwInvalidGraph(); |
| 34 | } |
| 35 | } else if (trimmedLine.startsWith('node ')) { |
| 36 | // no-op |
| 37 | } else if (trimmedLine.startsWith('"')) { |
| 38 | const edgeIndex = trimmedLine.indexOf('->'); |
| 39 | if (edgeIndex >= 0) { |
| 40 | const fromEdge = unquote(trimmedLine.slice(0, edgeIndex).trim()); |
| 41 | const toEdge = unquote(trimmedLine.slice(edgeIndex + 2).trim()); |
| 42 | graph.addEdge(fromEdge, toEdge); |
| 43 | } else { |
| 44 | graph.getOrCreateNode(unquote(trimmedLine)) |
| 45 | } |
| 46 | } else { |
| 47 | this.throwInvalidGraph(); |
| 48 | } |
| 49 | |
| 50 | index++; |
| 51 | } |
| 52 | |
| 53 | return graph; |
| 54 | } |
| 55 | |
| 56 | private static throwInvalidGraph(): never { |
| 57 | throw new Error('Could not parse digraph'); |
no test coverage detected