Created
December 28, 2022 19:06
-
-
Save rickychilcott/b6e74cedb5707c9fcb891d2fb74addb6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require "active_support/all" | |
Resource = Struct.new(:absolute_path) | |
paths = [ | |
Resource.new("/bread/crumbs/three"), | |
Resource.new("/bread"), | |
Resource.new("/bread/crumbs"), | |
Resource.new("/bread/crumbs/one"), | |
Resource.new("/bread/crumbs/two"), | |
Resource.new("/pages/two"), | |
Resource.new("/pages/three") | |
] | |
class FastAbsoluteLookup | |
def initialize(paths) | |
@paths = paths | |
end | |
def find(path:) | |
sections = path.split("/") | |
finder = sections.slice(1..-2) | |
smart_index.dig("/", *finder, :resources)&.find { |r| r.absolute_path == path } | |
end | |
private | |
def smart_index | |
@smart_index ||= begin | |
r = {} | |
@paths.each do |input| | |
path_sections = input.absolute_path.split("/") | |
relevant_path_segements = ["/", *path_sections.slice(1..-2)] | |
insert_resource_on_segement = relevant_path_segements.last | |
# Instantiate the hash for each section | |
relevant_path_segements.size.times do |index| | |
instantiation_segements = relevant_path_segements.slice(0..index) | |
if instantiation_segements.one? | |
r[instantiation_segements.last] ||= { | |
resources: [] | |
} | |
else | |
h = r.dig(*instantiation_segements.slice(0..-2)) | |
h[instantiation_segements.last] ||= { | |
resources: [] | |
} | |
end | |
end | |
r.dig(*relevant_path_segements)[:resources] << input | |
end | |
r.with_indifferent_access | |
end | |
end | |
end | |
lookup = FastAbsoluteLookup.new(paths) | |
pp lookup.find(path: "/bread/crumbs/two") | |
pp lookup.find(path: "/bread/crumbs") | |
pp lookup.find(path: "/bread") | |
pp lookup.find(path: "/blarg/target") # should be nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment