Skip to content

Instantly share code, notes, and snippets.

@asmallteapot
Last active April 17, 2023 01:12
Show Gist options
  • Save asmallteapot/70e6a954dacfdd0ed87b012599d44bed to your computer and use it in GitHub Desktop.
Save asmallteapot/70e6a954dacfdd0ed87b012599d44bed to your computer and use it in GitHub Desktop.
Code koan: Normalizing URLs in Swift 4
// 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