]> git.r.bdr.sh - rbdr/map/blame_incremental - Map/Logic/MapParser/Strategies/OpportunityParserStrategy.swift
Map 3 first commit: files, groups and layout
[rbdr/map] / Map / Logic / MapParser / Strategies / OpportunityParserStrategy.swift
... / ...
CommitLineData
1import Foundation
2
3struct OpportunityParserStrategy: MapParserStrategy {
4 private let regex = MapParsingPatterns.opportunity
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 == 5
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 multiplier = CGFloat(
18 String(line[Range(match.range(at: 3), in: line)!]) == "-" ? -1.0 : 1.0)
19 let vertex = String(line[Range(match.range(at: 2), in: line)!])
20 let opportunityString = String(line[Range(match.range(at: 4), in: line)!])
21 let opportunity = CGFloat(
22 truncating: NumberFormatter().number(from: opportunityString) ?? 0.0)
23
24 if let origin = vertices[vertex] {
25 let destination = CGPoint(
26 x: origin.position.x + opportunity * multiplier, y: origin.position.y)
27 let opportunity = Opportunity(id: index, origin: origin.position, destination: destination)
28 return (Opportunity.self, opportunity)
29 }
30
31 return (NSObject.self, NSObject()) // No matching object
32 }
33}