Created
February 17, 2016 16:38
-
-
Save dzucconi/b87ea7c06cf38765cf28 to your computer and use it in GitHub Desktop.
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
class Redirector | |
FALLBACK = '/' | |
def self.url(a) | |
match(a)[:key] | |
end | |
def self.handle(url) | |
RedirectTable::MAP[url] || url(url) || FALLBACK | |
end | |
private | |
def self.distance(a, b) | |
[(0..a.size).to_a].tap { |mx| | |
(1..b.size).each do |j| | |
mx << [j] + [0] * (a.size) | |
end | |
(1..b.size).each do |i| | |
(1..a.size).each do |j| | |
mx[i][j] = if a[j - 1] == b[i - 1] | |
mx[i-1][j-1] | |
else | |
[mx[i-1][j], mx[i][j-1], mx[i-1][j-1]].min + 1 | |
end | |
end | |
end | |
}[-1][-1] | |
end | |
def self.keys | |
@client ||= Client.new cache: true | |
@sidebar ||= Sidebar.new @client | |
@sidebar.links.map(&:href) | |
end | |
def self.match(a) | |
keys.map { |key| { key: key, distance: distance(a, key) } }.min_by { |hsh| hsh[:distance] } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment