I am working on an Excel like webApp, and I want to implement a function to let user insert rows freely. I can easily modify frontend to visualize where to insert by splice and selected row id, but our backend is using mongoDB that generates _id and order by default. To solve this problem we generate before and after Ids and come up newId in between before and after.
if (this.state.insertIndex !== undefined && this.state.insertIndex !== 0 && this.state.insertIndex !== rows.length - 1) {
const after = parseInt(rows[Math.max(this.state.insertIndex - 1, 0)]._id.toString().substring(0, 8), 16) * 1000;
const before = parseInt(rows[Math.min(this.state.insertIndex + 1, rows.length - 1)]._id.toString().substring(0, 8), 16) * 1000;
const timestampAsInteger = Math.floor(Math.random() * (after - before) + before);
newId = Math.floor(timestampAsInteger / 1000).toString(16) + "0000000000000000";
}
Note: insertIndex initial undefined, setState when cell selected, and reset to undefined after row deletion
However, this algorithm seems to have many edge cases not considered, does anyone have experience to make it more robust? or any suggestion on edge cases?
Known Issue:
- wrong behavior when select row[0]
- generating dup _id (not knowing why)
Other ideas
- Instead of generating _id, would it be easier to save the row state by localStorage render as the user see.
- I found this enter link description here but not understand, could anyone explain if its a possible solution?
Any thoughts? Many thanks