Created
February 26, 2018 10:27
-
-
Save giginet/37dbae11c9a157da776d7faf44d0f8df to your computer and use it in GitHub Desktop.
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 | |
private let separator: Character = "." | |
private let allWildcard = "**" | |
private let wildcard = "*" | |
func isValidPattern(_ pattern: String) -> Bool { | |
let patternElements = pattern.split(separator: separator, omittingEmptySubsequences: false) | |
let isValidWildcardCount = patternElements.filter { $0 == allWildcard || $0 == wildcard }.count <= 1 | |
let containsInvalidElement = patternElements.contains { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } | |
return isValidWildcardCount && !containsInvalidElement | |
} | |
func isValidPatternWithException(_ pattern: String) -> Bool { | |
enum ValidationError: Error { | |
case invalidElement | |
} | |
let elements = pattern.split(separator: separator, omittingEmptySubsequences: false) | |
let wildcards = try? elements.filter { element in | |
guard !element.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw ValidationError.invalidElement } | |
return element == allWildcard || element == wildcard | |
} | |
return wildcards.map { $0.count <= 1 } ?? false | |
} | |
func doBenchmark(execute: () -> Void) { | |
let date = Date() | |
execute() | |
print(Date().timeIntervalSince1970 - date.timeIntervalSince1970) | |
} | |
doBenchmark { | |
for a in (0..<1000000) { | |
isValidPattern("a.b..c") | |
} | |
} | |
doBenchmark { | |
for a in (0..<1000000) { | |
isValidPatternWithException("a.b..c") | |
} | |
} |
Author
giginet
commented
Feb 26, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment