All files / helpers/diff diff-match-patch.engine.ts

100% Statements 11/11
100% Branches 0/0
100% Functions 2/2
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  1x   1x 1x 1x   1x           1x   8x 8x 8x   13x            
import type { DiffChange, DiffEngine } from './diff.types';
import DiffMatchPatch from 'diff-match-patch';
 
const DIFF_DELETE = -1;
const DIFF_INSERT = 1;
const DIFF_EQUAL = 0;
 
const DIFF_TYPE_MAP: Record<number, DiffChange['type']> = {
    [DIFF_EQUAL]: 'equal',
    [DIFF_INSERT]: 'insert',
    [DIFF_DELETE]: 'delete',
};
 
export class DiffMatchPatchEngine implements DiffEngine {
    computeDiff(oldText: string, newText: string): DiffChange[] {
        const dmp = new DiffMatchPatch();
        const diffs = dmp.diff_main(oldText, newText);
        dmp.diff_cleanupSemantic(diffs);
 
        return diffs.map((diff: [number, string]) => ({
            type: DIFF_TYPE_MAP[diff[0]],
            text: diff[1],
        }));
    }
}