Given a plain array of values, e.g.
["Apple", "Orange", "Banana", "Strawberry"]
and a list of operations from the set of [insert
, delete
, sort
and replace
], e.g.
[
{cmd: "insert", index: 2, entries: ["Cherry", "Kiwi"]},
{cmd: "delete", indices: [3]},
{cmd: "sort", newOrder: [3,1,2,0,4]},
{cmd: "insert", index: 3, entries: ["Peach"]},
{cmd: "replace", index: 3, newEntry: "Raspberry"}
]
which should result in the array
["Banana", "Orange", "Cherry", "Raspberry", "Apple", "Strawberry"]
How can I, with relatively little effort, transform my sequence of operations into something less redundant? E.g.
[
{cmd: "sort", newOrder: [2,1,0,3]},
{cmd: "insert", index: 2, entries: ["Cherry", "Raspberry"]}
]
Note that deleting an entry and then inserting an identical one is considered equivalent to adding a completely new entry, whereas inserting a new entry and later deleting cancels out. Edits/replacements/renames of entries need to be kept track of, but they don't combine with any of the other operations.
Question:
This seems like something that would come up in the context of database query optimization, but I have no idea what to google for. I'm ultimately looking for an algorithm (preferably a JS implementation) that automates this kind of thing for me, if only in a naïve/greedy fashion (it doesn't have to exhaustively search for the best reduction, if it can't be done in polynomial time).
Background:
This came up while working on a web app in which the user can edit a list of entries, accept and submit those edits, and they then trigger a reshuffling of a set of corresponding arrays on the server. That means that I have to capture how the elements move around in the array, not just what the array looks like after all the changes are done. (I need to keep track of the operations for undo/redo functionality anyway.) Since the amount of data involved can be quite large, combining those operations before sending them would translate to shorter uploading times and fewer database writes server-side. All of this is purely theoretical at this point and may well amount to premature optimization, but I found it an interesting problem and would love some input.