Last active
April 17, 2023 01:12
-
-
Save asmallteapot/70e6a954dacfdd0ed87b012599d44bed to your computer and use it in GitHub Desktop.
Code koan: Normalizing URLs in Swift 4
This file contains 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
// https://en.wikipedia.org/wiki/URL_normalization | |
import Foundation | |
extension URLComponents { | |
typealias NormalizationRule = (_ components: URLComponents) -> URLComponents | |
func normalize(with rule: NormalizationRule) -> URLComponents { | |
return rule(self) | |
} | |
} | |
let identity: URLComponents.NormalizationRule = { $0 } // URLComponentsNormalizationRuleIdentity | |
let declutterUTM: URLComponents.NormalizationRule = { components in | |
var normalized = components | |
normalized.queryItems = components.queryItems?.filter { !$0.name.starts(with: "utm_") } | |
return normalized | |
} | |
let removeEmptyQuery: URLComponents.NormalizationRule = { components in | |
if let query = components.query, query.isEmpty { | |
var normalized = components | |
normalized.query = nil | |
return normalized | |
} else { | |
return components | |
} | |
} | |
guard let sampleComponents = URLComponents(string: "https://github.com/hobby-kube/guide?utm_campaign=explore-email&utm_medium=email&utm_source=newsletter&utm_term=daily") else { | |
fatalError("Couldn't create sample URL components") | |
} | |
var components = sampleComponents | |
components = components.normalize(with: identity) | |
print(components.string) | |
// Optional("https://github.com/hobby-kube/guide?utm_campaign=explore-email&utm_medium=email&utm_source=newsletter&utm_term=daily") | |
components = components.normalize(with: declutterUTM) | |
print(components.string) | |
// Optional("https://github.com/hobby-kube/guide?") | |
components = components.normalize(with: removeEmptyQuery) | |
print(components.string) | |
// Optional("https://github.com/hobby-kube/guide") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment