在两个字符串上执行合并

时间:2017-03-07 19:31:14

标签: javascript algorithm

我正在尝试构建协作文档编辑器并实施运营转型。想象一下,我们有一个由2个用户同时操作的字符串。他们只能添加字符,而不能删除它们。我们想要结合他们的两个变化。

原始字符串为:catspider

第一位用户执行此操作:cat<span id>spider</span>

第二个用户执行此操作:c<span id>atspi</span>der

我正在尝试编写一个能产生:c<span id>at<span id>spi</span>der</span>

的函数

我写的函数很接近,但它产生c<span id>at<span i</span>d>spider</span> codepen here

String.prototype.splice = function(start, newSubStr) {
    return this.slice(0, start) + newSubStr + this.slice(start);
};

function merge(saved, working, requested) {
    if (!saved || !working || !requested) {
        return false;
    }

    var diffSavedWorking = createDiff(working, saved);
    var diffRequestedWorking = createDiff(working, requested);

    var newStr = working;

    for (var i = 0; i < Math.max(diffRequestedWorking.length, diffSavedWorking.length); i++) {

        //splice does an insert `before` -- we will assume that the saved document characters
        //should always appear before the requested document characters in this merger operation
        //so we first insert requested and then saved, which means that the final string will have the
        //original characters first.

        if (diffRequestedWorking[i]) {

            newStr = newStr.splice(i, diffRequestedWorking[i]);

            //we need to update the merge arrays by the number of 
            //inserted characters.
            var length = diffRequestedWorking[i].length;
            insertNatX(diffSavedWorking, length, i + 1);
            insertNatX(diffRequestedWorking, length, i + 1);
        }

        if (diffSavedWorking[i]) {
            newStr = newStr.splice(i, diffSavedWorking[i]);

            //we need to update the merge arrays by the number of 
            //inserted characters.
            var length = diffSavedWorking[i].length;
            insertNatX(diffSavedWorking, length, i + 1);
            insertNatX(diffRequestedWorking, length, i + 1);
        }
    }
    return newStr;
}

//arr1 should be the shorter array.
//returns inserted characters at their 
//insertion index.
function createDiff(arr1, arr2) {
    var diff = [];
    var j = 0;
    for (var i = 0; i < arr1.length; i++) {
        diff[i] = "";
        while (arr2[j] !== arr1[i]) {
            diff[i] += arr2[j];
            j++;
        }
        j++;
    }
    var remainder = arr2.substr(j);
    if (remainder) diff[i] = remainder;
    return diff;
}

function insertNatX(arr, length, pos) {
    for (var j = 0; j < length; j++) {
        arr.splice(pos, 0, "");
    }
}

var saved =     'cat<span id>spider</span>';
var working =   'catspider';
var requested = 'c<span id>atspi</span>der';

console.log(merge(saved, working, requested));

对于实现这一目标的更好/更简单的方法有任何想法。

0 个答案:

没有答案