diff options
Diffstat (limited to 'Map/MapParser/Strategies/EdgeParserStrategy.swift')
| -rw-r--r-- | Map/MapParser/Strategies/EdgeParserStrategy.swift | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/Map/MapParser/Strategies/EdgeParserStrategy.swift b/Map/MapParser/Strategies/EdgeParserStrategy.swift new file mode 100644 index 0000000..0df1ff4 --- /dev/null +++ b/Map/MapParser/Strategies/EdgeParserStrategy.swift @@ -0,0 +1,32 @@ +import Foundation + +struct EdgeParserStrategy: MapParserStrategy { + private let regex = MapParsingPatterns.edge + + func canHandle(line: String) -> Bool { + let range = NSRange(location: 0, length: line.utf16.count) + let matches = regex.matches(in: String(line), options: [], range: range) + return matches.count > 0 && matches[0].numberOfRanges == 4 + } + + func handle(index: Int, line: String, vertices: [String: Vertex]) -> (Any.Type, Any) { + let range = NSRange(location: 0, length: line.utf16.count) + let matches = regex.matches(in: String(line), options: [], range: range) + + let match = matches[0] + let arrowhead = String(line[Range(match.range(at: 2), in: line)!]) == ">" + let vertexA = String(line[Range(match.range(at: 1), in: line)!]) + let vertexB = String(line[Range(match.range(at: 3), in: line)!]) + + if let origin = vertices[vertexA] { + if let destination = vertices[vertexB] { + let edge = MapEdge( + id: index, origin: origin.position, destination: destination.position, + arrowhead: arrowhead) + return (MapEdge.self, edge) + } + } + + return (NSObject.self, NSObject()) // No matching object + } +} |