Created
November 24, 2018 17:20
-
-
Save iSapozhnik/100343d483221f0542e166f9c151d228 to your computer and use it in GitHub Desktop.
Haptico pattern with duration parser
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
import Foundation | |
class Impact { | |
private let duration: Int | |
init(with string: String) { | |
let result = string.replacingOccurrences( of:"[Oo.()]{1,}", with: "", options: .regularExpression) | |
self.duration = Int(result)! | |
} | |
var description: String { | |
return "Duration: \(self.duration)" | |
} | |
} | |
class BigImpact: Impact { | |
} | |
class MediumImpact: Impact { | |
} | |
class SmallImpact: Impact { | |
} | |
class ImpactFactory { | |
static func impact(for string: String) -> Impact { | |
let startIndex = string.startIndex | |
let substring = string[startIndex] | |
switch substring { | |
case "O": | |
return BigImpact(with: string) | |
case "o": | |
return MediumImpact(with: string) | |
case ".": | |
return SmallImpact(with: string) | |
default: | |
print("Error occured: \(substring)") | |
return Impact(with: "") | |
} | |
} | |
} | |
let pattern = "O(4)o(4)" | |
let string = "O(4)o(4).(18).(180)" | |
let regex = try! NSRegularExpression(pattern: "((O|o|.){1})([(]{1})([0-9]{1,3})([)]{1})") | |
let range = NSRange(string.startIndex..., in: string) | |
let results = regex.matches(in: string, options: .anchored, range: range) | |
.map { match -> Substring in | |
let range = Range(match.range(at: 0), in: string)! | |
return string[range] | |
} | |
let impacts: [Impact] = results.map { substring in | |
guard let substring = substring as? Substring else { return BigImpact(with: "") } | |
let string = String(substring) | |
return ImpactFactory.impact(for: string) | |
} | |
impacts.forEach { print($0.description) } | |
print(impacts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment