我有两个数组,分别表示故事列表。两个用户可以同时修改顺序、添加或删除故事,我想要将这些更改合并。
以下示例可能会更加清晰
Original 1,2,3,4,5
UserA (mine) 3,1,2,4,5 (moved story 3 to start)
UserB (theirs) 1,2,3,5,4 (moved story 5 forward)
以上操作的结果应该是:
Merge (result) 3,1,2,5,4
在冲突的情况下,用户A应始终获胜。
我用这种简单的方法取得了很大的进展。首先,我删除了我的代码中应该删除的部分(该部分代码未显示,因为它是微不足道的),然后我迭代我的代码,插入并移动他们的代码中所需的内容(mstories = mine,tstories = theirs):
for (var idx=0;idx<mstories.length;idx++) {
var storyId = mstories[idx];
// new story by theirs
if (tstories[idx] !== undefined && mstories.indexOf(tstories[idx]) == -1) {
mstories.splice(idx+1, 0, tstories[idx]);
idx--;
continue;
}
// new story by mine
if (tstories.indexOf(storyId) == -1 && ostories.indexOf(storyId) == -1) {
tstories.splice(idx+offset, 0, storyId);
offset += 1;
// story moved by me
} else if ((tstories.indexOf(storyId) != idx + offset) && ostories.indexOf(storyId) != idx) {
tstories.splice(tstories.indexOf(storyId), 1);
tstories.splice(idx+offset, 0, storyId);
// story moved by them
} else if (tstories.indexOf(storyId) != idx + offset) {
mstories.splice(mstories.indexOf(storyId), 1);
mstories.splice(idx+offset, 0, storyId);
mdebug(storyId, 'S moved by them, moffset--');
}
}
result = tstories
这个问题很接近解决,但当太多的故事被移到前面或后面并且中间有其他用户触摸的故事时,它会变得混乱。
我有一个扩展版本,对原始内容进行检查并更加智能 - 持有2个偏移量等等,但我觉得这是一个必须有a)名称b)完美解决方案的问题,我不想重新发明轮子。