Created
November 19, 2015 00:50
-
-
Save coryalder/573116711a2e03539f8c to your computer and use it in GitHub Desktop.
Autocomplete filter code from Rivet's autocomplete suggestion engine
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
// depends on https://github.com/coryalder/LevenshteinSwift | |
class SuggestionController { | |
// has a couple of notable vars: | |
// delegate, where the inputted text is loaded from | |
// rawCompletions, an array of possible suggestions (unfiltered) | |
// autocompletions, the filtered array of suggestions we're offer up to the user | |
func filterAutocompletions() { | |
let campaignField = delegate!.campaignField | |
let _ = delegate?.longUrl | |
guard let string = campaignField.text where string.characters.count > 0 else { | |
self.autocompletions = self.rawCompletions | |
suggestionTable.reloadData() | |
return | |
} | |
var mapped = rawCompletions.map { | |
($0.limit(string.characters.count).asciiLevenshteinDistance(string), $0) | |
} | |
mapped.sortInPlace { | |
$0.0 < $1.0 | |
} | |
let resultsCount = max(mapped.count - 1, 0) | |
let lim = min(resultsCount, 10) | |
// protect against 0...lim when lim == 0 | |
let slice: Array<(Int, String)> = { | |
if lim > 0 { | |
return Array(mapped[0...lim]) | |
} else { | |
return mapped | |
} | |
}() | |
let out = slice.map { | |
$0.1 | |
} | |
self.autocompletions = out | |
suggestionTable.reloadData() | |
} | |
} | |
// limit strings to a specific length. "twitter".limit(2) == "tw" | |
public extension String { | |
func limit(n: Int) -> String { | |
let actual = min(self.characters.count, n) | |
let ind = startIndex.advancedBy(actual) | |
return substringToIndex(ind) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment