Created
March 12, 2010 23:12
-
-
Save stalcottsmith/330917 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
module Abbreviator | |
def self.abbreviate(names) | |
abbrs = names.sort.inject({}) do |hash, name| | |
hash[name] = replace_non_word_chars(name).slice(0,3) | |
hash | |
end | |
Hash[*abbrs.map do |name, abbr| | |
[name, | |
(abbrs.values.select{|v|v.eql?(abbr)}.size == 1) ? abbr : | |
resolve_conflict(abbr, name, [abbrs.select{|k,v| v.eql?(abbr)}.map(&:first)-[name]].flatten)] | |
end.flatten] | |
end | |
private | |
def self.replace_non_word_chars(s) | |
s.gsub(/\W/, '') | |
end | |
def self.resolve_conflict(abbr, name, conflicts) | |
conflict_chars = conflicts.map {|c| replace_non_word_chars(c).split('')} | |
abbr + (replace_non_word_chars(name).split('').detect do |char| | |
!conflict_chars.map {|c| c.shift}.include?(char) | |
end || '') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment