User table with insert, update, remove, and bounded undo/redo
The members page of an admin dashboard lets support agents add, edit, and remove users, and press Undo or Redo afterwards. The list on screen has a fixed order, so undoing a removal must put the user back exactly where it was, not at the bottom. Memory is limited, so only the latest steps can be undone.
Implement a class UserTable.
const table = new UserTable({ historyLimit }?);
table.insert(user) // => the stored user (a copy)
table.update(id, patch) // => the updated user (a copy)
table.remove(id) // => boolean: true if a user was removed
table.get(id) // => a copy of the user, or null
table.list() // => copies of all users, in table order
table.undo() // => boolean
table.redo() // => boolean
id, a string email, and any other fields (strings, numbers, booleans, null).Ana@Acme.io and ana@acme.io conflict.insert or update, never changes the table.insert(user) adds the user at the end of the table. It throws an Error if the id or the email is already used.update(id, patch) shallow-merges patch into the user and keeps its position. It throws an Error if no user has that id, if patch contains an id key, or if the new email is used by another user. If every value in patch already equals the current value (Object.is), nothing is recorded.remove(id) removes the user and returns true, or returns false if no user has that id.list() returns users in table order: insertion order, with removed users gone.false, or changes nothing leaves the users and the history exactly as they were.undo() reverts the latest step and returns true, or returns false if there is nothing to undo. Reverting a removal puts the user back at its original position. Reverting an update restores the user exactly as it was, so fields the patch added disappear again.redo() re-applies the latest undone step and returns true, or returns false if there is nothing to redo.historyLimit is optional (default: no limit). When recording a step would keep more than historyLimit undo steps, the oldest one is dropped and can no longer be undone.const table = new UserTable({ historyLimit: 10 });
table.insert({ id: 'u1', email: 'ana@acme.io', role: 'admin' });
table.insert({ id: 'u2', email: 'raj@acme.io', role: 'viewer' });
table.insert({ id: 'u3', email: 'kim@acme.io', role: 'viewer' });
table.insert({ id: 'u4', email: 'ANA@acme.io' }); // throws: email in use
table.update('u2', { role: 'editor', team: 'growth' });
table.remove('u2'); // => true
table.list().map((u) => u.id); // => ['u1', 'u3']
table.undo(); // => true (u2 is back in the middle)
table.list().map((u) => u.id); // => ['u1', 'u2', 'u3']
table.undo(); // => true
table.get('u2'); // => { id: 'u2', email: 'raj@acme.io', role: 'viewer' }
table.redo(); // => true
table.get('u2').team; // => 'growth'