Created
January 13, 2022 18:13
-
-
Save rwehresmann/50727076c1402789368ecfeeb9b8ea8e 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 FakeRedis | |
| attr_reader :counts, :vars | |
| def initialize(counts: {}, vars: {}) | |
| @counts = counts | |
| @vars = vars | |
| end | |
| def set(var, val) | |
| @vars[var] = val | |
| if @counts[val] | |
| @counts[val] = @counts[val] + 1 | |
| else | |
| @counts[val] = 1 | |
| end | |
| end | |
| def get(var) | |
| if @vars[var] | |
| puts @vars[var] | |
| else | |
| puts "NULL" | |
| end | |
| end | |
| def unset(var) | |
| val = @vars[var] | |
| @vars.delete(var) | |
| @counts[val] = @counts[val] - 1 if val | |
| end | |
| def numequal_to(val) | |
| puts @counts[val] || 0 | |
| end | |
| end | |
| transactions = [] | |
| base_pr = FakeRedis.new | |
| current_pr = base_pr | |
| while true do | |
| comm = STDIN.gets | |
| args = comm.split(" ") | |
| case args[0] | |
| when "SET" | |
| current_pr.set(args[1], args[2]) | |
| when "GET" | |
| current_pr.get(args[1]) | |
| when "UNSET" | |
| current_pr.unset(args[1]) | |
| when "NUMEQUALTO" | |
| current_pr.numequal_to(args[1]) | |
| when "END" | |
| exit | |
| when "BEGIN" | |
| new_pr = FakeRedis.new( | |
| counts: current_pr.counts.dup, | |
| vars: current_pr.vars.dup | |
| ) | |
| transactions << new_pr | |
| current_pr = new_pr | |
| when "ROLLBACK" | |
| if transactions.empty? | |
| puts "NO TRANSACTION" | |
| elsif transactions.length == 1 | |
| transactions.pop | |
| current_pr = base_pr | |
| else | |
| transactions.pop | |
| current_pr = transactions.last | |
| end | |
| when "COMMIT" | |
| if transactions.empty? | |
| puts "NO TRANSACTION" | |
| else | |
| current_pr = transactions.last | |
| base_pr = current_pr | |
| transactions = [] | |
| end | |
| else | |
| p "Failed with args #{args}" | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment