42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
|
import * as plugins from './smartdiff.plugins';
|
||
|
|
||
|
import diff from 'fast-diff';
|
||
|
|
||
|
export const createDiff = (originalArg: string, revisionArg: string) => {
|
||
|
var result = diff(originalArg, revisionArg);
|
||
|
// According to latest jsperf tests, there's no need to cache array length
|
||
|
for (var i = 0; i < result.length; i++) {
|
||
|
var diffItem = result[i];
|
||
|
// If operation is DELETE or EQUAL, replace the actual text by its length
|
||
|
if (diffItem[0] < 1) {
|
||
|
// @ts-ignore
|
||
|
diffItem[1] = diffItem[1].length;
|
||
|
}
|
||
|
}
|
||
|
return JSON.stringify(result);
|
||
|
};
|
||
|
|
||
|
export const applyPatch = (originalArg: string, deltaStringArg: string) => {
|
||
|
const deltaArg = JSON.parse(deltaStringArg);
|
||
|
var result = '',
|
||
|
index = 0;
|
||
|
|
||
|
// According to latest jsperf tests, there's no need to cache array length
|
||
|
for (var i = 0; i < deltaArg.length; i++) {
|
||
|
const item = deltaArg[i];
|
||
|
const operation = item[0];
|
||
|
const value = item[1];
|
||
|
|
||
|
if (operation === -1) {
|
||
|
// DELETE
|
||
|
index += value;
|
||
|
} else if (operation === 0) {
|
||
|
// KEEP
|
||
|
result += originalArg.slice(index, index += value);
|
||
|
} else {
|
||
|
// INSERT
|
||
|
result += value;
|
||
|
}
|
||
|
}
|
||
|
return result;
|
||
|
};
|