Skip to content

Instantly share code, notes, and snippets.

@dcutting
Created November 15, 2016 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcutting/6ae7f194afd0a10739d59f77071b6695 to your computer and use it in GitHub Desktop.
Save dcutting/6ae7f194afd0a10739d59f77071b6695 to your computer and use it in GitHub Desktop.
Looks up how many UK companies exist for all 2-permutations of a given list of words.
import Foundation
func boxdrive() {
let words = ["drop", "box", "live", "drive"]
let template = "https://beta.companieshouse.gov.uk/search?q={name}"
let permutations = blended(words: words)
let results = fetchResults(for: permutations, template: template)
print(results)
}
func blended(words: [String]) -> [String] {
return words.flatMap { first in
words.flatMap { second in
guard first != second else { return nil }
return "\(first)\(second)"
}
}
}
func fetchResults(for words: [String], template: String) -> [(String, Int?)] {
return words.map { word in
guard let url = makeURL(for: word, template: template) else { return (word, nil) }
let result = fetchResult(from: url)
return (word, result)
}
}
func makeURL(for word: String, template: String) -> URL? {
let prepared = template.replacingOccurrences(of: "{name}", with: word)
return URL(string: prepared)
}
func fetchResult(from url: URL) -> Int? {
let request = makeRequest(for: url)
guard let data = data(for: request) else { return nil }
return extractTotalResults(from: data)
}
func makeRequest(for url: URL) -> URLRequest {
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Accept")
return request
}
func data(for request: URLRequest) -> Data? {
let semaphore = DispatchSemaphore(value: 0)
var returnData: Data?
let task = URLSession.shared.dataTask(with: request) { data, _, _ in
returnData = data
semaphore.signal()
}
task.resume()
semaphore.wait()
return returnData
}
func extractTotalResults(from data: Data) -> Int? {
do {
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
let totalResults = json?["total_results"]
return totalResults as? Int
} catch {
return nil
}
}
func print(_ results: [(String, Int?)]) {
results.forEach { (name, count) in
let count = count?.description ?? "error"
print("\(name): \(count)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment