Last active
March 7, 2025 20:43
-
-
Save teaforthecat/e98a57b8f2fca69ce54968ff3cd9e2a8 to your computer and use it in GitHub Desktop.
Hashli the tree based hash table
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
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