I've got an array
which gets updated by user input (keyboard). I want to keep track of what entries change to get a better live performance.
Here an example:
// ascii values for 'Stuckoverflow'
var previousBlocks = [
83, 116, 117, 99, 107, 111, 118,
101, 114, 102, 108, 111, 119
];
// ascii values for 'Stackedoverflow2014'
var blocks = [
83, 116, 97, 99, 107, 101, 100, 111, 118,
101, 114, 102, 108, 111, 119,
50, 48, 49, 52
];
I want to get the positions of entries that have been added or removed from previousBlocks
to blocks
. The larger unchanged part should remain intact. (In this case 'overflow')
var result = {
deletions: [2],
additions: [2, 5, 6, 13, 14, 15, 16]
};
Human readable, the difference could be expressed like this:
St[-u][+a]ck[+e][+d]overflow[+2][+0][+1][+4]
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
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.