]> git.r.bdr.sh - rbdr/map/blob - Map/Logic/MapParser/Strategies/EdgeParserStrategy.swift
0df1ff4fb0d25acab595113f411a727d10d1ddac
[rbdr/map] / Map / Logic / MapParser / Strategies / EdgeParserStrategy.swift
1 import Foundation
2
3 struct EdgeParserStrategy: MapParserStrategy {
4 private let regex = MapParsingPatterns.edge
5
6 func canHandle(line: String) -> Bool {
7 let range = NSRange(location: 0, length: line.utf16.count)
8 let matches = regex.matches(in: String(line), options: [], range: range)
9 return matches.count > 0 && matches[0].numberOfRanges == 4
10 }
11
12 func handle(index: Int, line: String, vertices: [String: Vertex]) -> (Any.Type, Any) {
13 let range = NSRange(location: 0, length: line.utf16.count)
14 let matches = regex.matches(in: String(line), options: [], range: range)
15
16 let match = matches[0]
17 let arrowhead = String(line[Range(match.range(at: 2), in: line)!]) == ">"
18 let vertexA = String(line[Range(match.range(at: 1), in: line)!])
19 let vertexB = String(line[Range(match.range(at: 3), in: line)!])
20
21 if let origin = vertices[vertexA] {
22 if let destination = vertices[vertexB] {
23 let edge = MapEdge(
24 id: index, origin: origin.position, destination: destination.position,
25 arrowhead: arrowhead)
26 return (MapEdge.self, edge)
27 }
28 }
29
30 return (NSObject.self, NSObject()) // No matching object
31 }
32 }