Store With Nested Transactions
Implement a class TxStore, a store of integer values under string keys whose changes can be grouped into transactions, and transactions can be nested. Write these methods:
TxStore()starts empty, with no open transaction.put(key, value)setskeytovalue.read(key)returns the value ofkey, or-1ifkeyis not set.count_equal(value)returns how many keys are set tovalue.begin()opens a new transaction inside the ones already open. Returns how many transactions are open now.rollback()undoes every change made since the innermost open transaction began, and closes it. Returns how many keys have a different value afterwards than just before (a key that becomes unset counts), or-1if no transaction is open.commit()closes the innermost open transaction and keeps its changes. If another transaction is still open, those changes now belong to it, so rolling it back undoes them too. Returns how many transactions are still open, or-1if none was open.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
TxStore()
put("a", 1)
begin() returns 1
put("a", 2)
put("b", 2)
begin() returns 2
put("c", 3)
commit() returns 1
read("c") returns 3
rollback() returns 3
read("a") returns 1
read("b") returns -1
The inner transaction is committed, so its change to c joins the outer one. Rolling back the outer transaction then puts a back to 1 and unsets b and c: three keys change.
Constraints
keyhas1or2lowercase letters0 <= value <= 9- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.