Skip to content

Instantly share code, notes, and snippets.

@teaforthecat
Last active March 7, 2025 20:43
Show Gist options
  • Save teaforthecat/e98a57b8f2fca69ce54968ff3cd9e2a8 to your computer and use it in GitHub Desktop.
Save teaforthecat/e98a57b8f2fca69ce54968ff3cd9e2a8 to your computer and use it in GitHub Desktop.
Hashli the tree based hash table
class Hashli
attr_accessor :store, :depth
def initialize()
self.depth = 3
init_store
end
def hash k
k.hash.to_s.chars.take(@depth).map(&:to_i)
end
def get k
store.dig(*hash(k))
end
def set(k,v)
*is, last = hash(k)
# ensure the branches are in place, then place the leaf
is.reduce(store) do |agg,i|
agg[i] ||= Array.new(10)
end[last] = v
self
end
def delete(k)
set(k, nil)
end
private
def init_store
# collapse arrays into a nested Tree-like structure
self.store = Array.new(depth){ Array.new(10) }.reduce do |agg, a|
a.append(agg)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment