Last active
June 6, 2020 06:24
-
-
Save sferik/8629c01c3be09439e36c76537f572054 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
class SizeAwareCache | |
@@cache = {} of String => Hash(Int32, String) | |
def read(key : String, size : Int32) | |
if value = @@cache.dig?(key, size) | |
# Hit! (both key and size) | |
return value | |
elsif results = @@cache[key]? | |
# Key hit, size miss | |
sorted_results = results.to_a.sort_by(&.first) | |
# Return the first element greater than the requested size (or the largest, if none are greater) | |
sorted_results.find { |tuple| return tuple[1] if tuple[0] > size || tuple == sorted_results.last } | |
else | |
# Miss | |
return nil | |
end | |
end | |
def write(key : String, value : String, size : Int32) | |
if @@cache[key]? | |
@@cache[key][size] = value | |
else | |
@@cache[key] = {size => value} | |
end | |
end | |
end | |
require "spec" | |
describe SizeAwareCache do | |
describe "#read" do | |
it "returns nil when key is not found" do | |
image_cache = SizeAwareCache.new | |
image_cache.read("foo", 100).should be_nil | |
end | |
it "returns an exact match" do | |
image_cache = SizeAwareCache.new | |
image_cache.write("user-1", "[email protected]", 100) | |
image_cache.read("user-1", 100).should eq("[email protected]") | |
end | |
it "returns the first image greater than the requested size" do | |
image_cache = SizeAwareCache.new | |
image_cache.write("user-1", "[email protected]", 100) | |
image_cache.write("user-1", "[email protected]", 200) | |
image_cache.write("user-1", "[email protected]", 300) | |
image_cache.read("user-1", 150).should eq("[email protected]") | |
end | |
it "returns the largest image below the requested size" do | |
image_cache = SizeAwareCache.new | |
image_cache.write("user-1", "[email protected]", 100) | |
image_cache.write("user-1", "[email protected]", 200) | |
image_cache.write("user-1", "[email protected]", 300) | |
image_cache.read("user-1", 400).should eq("[email protected]") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment