Created
August 6, 2020 21:27
-
-
Save coreyjs/7310df61ed9ee474edb3bc4693bf9128 to your computer and use it in GitHub Desktop.
File Server
This file contains 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 Storage | |
attr_accessor :value | |
def initialize | |
@value = nil | |
@map = {} # string, Storage | |
end | |
def map | |
@map | |
end | |
def to_s | |
map.each_key do |path| | |
puts "path #{path}, val: #{map[path].value}" | |
map[path].to_s | |
end | |
end | |
end | |
class FileSystem | |
def initialize | |
@root = Storage.new | |
end | |
def root | |
@root | |
end | |
def create(path, val) | |
# give us an array of the file path, [:a, :b] | |
paths = path.split('/').reject(&:empty?) | |
current = @root | |
paths[0, paths.length-1].each_with_index do |p, index| | |
#puts "index #{index} length: #{paths.length}" | |
if current.map.key?(p) == false | |
return false | |
else | |
current = current.map[p] | |
end | |
end | |
new_storage = Storage.new | |
new_storage.value = val | |
current.map[paths.last] = new_storage | |
true | |
end | |
def get(path) | |
paths = path.split('/').reject(&:empty?) | |
return -1 if paths.empty? | |
current = @root | |
paths.each_with_index do |p, i| | |
if current.map.key?(p) == false | |
return -1 | |
else | |
current = current.map[p] | |
end | |
end | |
current.value | |
end | |
def make_dir(path) | |
paths = path.split('/').reject(&:empty?) | |
return false if paths.empty? | |
current = @root | |
paths.each_with_index do |p, i| | |
# if we dont find /DIR/, add it | |
if current.map.key?(p) == false | |
current.map[p] = Storage.new | |
current = current.map[p] | |
end | |
end | |
end | |
end | |
f = FileSystem.new | |
puts "got: #{f.create("/a", 1)}, expect: true" # true | |
puts "got: #{f.create("/b", 2)}, expect: true" # true | |
puts "got: #{f.create("/bad/path", 3) }, expect: false" #false | |
puts "got: #{f.create("/a/aa", 5)}, expect: true" # true | |
puts "got: #{f.create("/a/aa/aaa", 10)}, expect: true" # true | |
puts "wanted: 1, got #{f.get("/a")}" | |
puts "wanted: -1, got #{f.get("/adsfsdf")}" | |
puts "wanted: 10, got #{f.get("/a/aa/aaa")}" | |
f.make_dir('/z/zz/zzzz/zzzz') | |
puts "wanted: 1000202030, got #{f.create('/z/zz/zzzz/zzzz', 1000202030)}" | |
f.root.to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment