这是返回可以插入项目的位置(以回调的形式)并更新先前项目的位置的算法。
Put the item into infinite length array (assumed), 0<=index<INFINITY,
and for empty array largest_index_occupied = 0. ALSO largest_index_occupied is dynamically retrieved from database.(assumed). No two item can share same index. No item must be lost during any operation. indexes are in increasing order.
1. if index not provided OR index provided is greater than largest_index_occupied then put item at index : largest_index_occupied+5;
2. If index provided AND less than equals to largest_index_occupied, :
a. if (No other item already exists at that index) : simply put the item at that index
b. otherwise (means if a item already exists at that index) : increase the index of all items by one untill we get an empty index. and put the new item at the index actually passed by user(which must be empty now).
2.b 示例:
说 - 显示空索引。
以前的状态
0 - - - - 5 6 7 - - 10
a - - - - b c d - - e
在索引处输入:5,f
新状态:
0 - - - - 5 6 7 8 - 10
a - - - - f b c d - e
Noe f 的新指数为 5。
我的要求是在nodejs中结合异步,递归和IO操作(db更新-在2.b的情况下为项目的索引)编写上述代码。
我期待next(err,indexToBeInserted);
只有在所有更新发生后才能调用的回调。
我的功能块在这里:
toInsert(mongooseModel,next,indexToBeInserted) {
// async code goes here.
}
ps:如果您有更好的解决方案,请分享。