Delta编码 - 字符串(编程逻辑 - 没有特定语言)

时间:2016-07-04 13:17:10

标签: delta

任何人都可以为字符串添加delta编码代码。

例如,如果初始字符串是

  

“猫与狗”

以后字符串是

  

“猫与狗”

我应该能够非常有效地获得字符串版本之间的差异。如果有人可以在这里放置代码,那么可以使用delta编码以非常少的数据发送非常大的段落。

1 个答案:

答案 0 :(得分:1)

我找到了答案,我想与大家分享。

var oldString = "This is just a sample of string to test the delta encoding. Infact, with my own login.dsfdsfdsfdsfsdfsdfdsfdsfsdfsdfds  dsfds fds fddsf";
var newString = "dsfdsThissdf is just a sample of string to test X the dedsfdsflta encoding sdfds decoding. Infact, with my own sadsadsadsad"
var result = "";

var changes = getChanges(oldString, newString);
var string = getOriginal(oldString, changes);

function getChanges(os, ns) {
    var addedIndex = false;
    var changes = [];
    var obj = [];
    var oi = 0, ni = 0;
    while (oi < oldString.length && ni < newString.length) {
        if (newString.charAt(ni) != oldString.charAt(oi)) {
            if (!addedIndex) {
                obj.push(oi);
                obj.push(newString.charAt(ni));
                addedIndex = true;
            }
            else {
                obj[1] += newString.charAt(ni);
            }
            ni++;
        }
        else {
            if (addedIndex) {
                changes.push(obj);
                obj = [];
                addedIndex = false;
            }
            oi++;
            ni++;
        }
    };
    if (addedIndex) {
        changes.push(obj);
        obj = [];
        addedIndex = false;
    }
    obj = [];
    if (ni == newString.length) {
        obj.push(-1 * oi);
        changes.push(obj);
    }
    if (oi == oldString.length) {
        obj.push(ni);
        obj.push(newString.substring(ni));
        changes.push(obj);
    }
    return changes;
}

function getOriginal(os, changes) {
    var result = os;
    for (var i = changes.length - 1; i >= 0  ; i--) {
        if (changes[i][0] < 0) {
            result = result.substring(0, -1 * changes[i][0]);
        }
        else {
            result = result.substring(0, changes[i][0]) + changes[i][1] + result.substring(changes[i][0]);
        }
    };
    return result;
}

console.log(string);
console.log(newString);