1 # frozen_string_literal: true
 
   3 # A map of each OSM key to its formatter URL. For example:
 
   4 # { "ref:vatin" => "https://example.com/$1" }
 
   5 # The JSON data is an array with duplicate entries, which is not efficient for lookups.
 
   6 # So, convert it to a hash and only keep the item with the best rank.
 
   7 TAG2LINK = JSON.parse(Rails.root.join("node_modules/tag2link/index.json").read)
 
   8                # exclude deprecated and third-party URLs
 
   9                .reject { |item| item["rank"] == "deprecated" || item["source"] == "wikidata:P3303" }
 
  10                .group_by { |item| item["key"] }
 
  11                .transform_keys { |key| key.sub(/^Key:/, "") }
 
  12                # move preferred to the start of the array
 
  13                .transform_values { |items| items.sort_by { |item| item["rank"] == "preferred" ? 0 : 1 }.uniq { |item| item["url"] } }
 
  14                # exclude any that are ambiguous, i.e. the best and second-best have the same rank
 
  15                .reject { |_key, value| value[1] && value[0]["rank"] == value[1]["rank"] }
 
  16                # keep only the best match
 
  17                .transform_values { |items| items[0]["url"] }