w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Get the difference (additions and deletions) between two arrays / strings

Because the array gets manipulated by the user (by typing), changes are clustered. This solution calculates one range of changes and determines the replacement blocks. It is a very easy solution but it does its job.

var start = 0;
var end = 0;
var length = Math.min(previousBlocks.length, length);

// compare from left to right
while (
    start < length
    && previousBlocks[start]
        == blocks[start]
) {
    start ++;
}

// compare from right to left
while (
    end < length - start
    && previousBlocks[previousBlocks.length - end - 1]
        === blocks[blocks.length - end - 1]
) {
    end ++;
}

// collect the blocks that have been added
var rangeBlocks = [];
for (var i = start; i < blocks.length - end; i ++)
{
    rangeBlocks.push(blocks[i]);
}

return {
    // unchanged amount of blocks on the left
    startOffset: start,

    // unchanged amount of blocks on the right
    endOffset: end,

    // exchange / replace the changed part by these blocks
    blocks: rangeBlocks
};




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.