| 9 | import {DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff} from './cleanupSemantic'; |
| 10 | |
| 11 | const diffStrings = (a: string, b: string): Array<Diff> => { |
| 12 | const isCommon = (aIndex: number, bIndex: number) => a[aIndex] === b[bIndex]; |
| 13 | |
| 14 | let aIndex = 0; |
| 15 | let bIndex = 0; |
| 16 | const diffs: Array<Diff> = []; |
| 17 | |
| 18 | const foundSubsequence = ( |
| 19 | nCommon: number, |
| 20 | aCommon: number, |
| 21 | bCommon: number, |
| 22 | ) => { |
| 23 | if (aIndex !== aCommon) { |
| 24 | diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex, aCommon))); |
| 25 | } |
| 26 | if (bIndex !== bCommon) { |
| 27 | diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex, bCommon))); |
| 28 | } |
| 29 | |
| 30 | aIndex = aCommon + nCommon; // number of characters compared in a |
| 31 | bIndex = bCommon + nCommon; // number of characters compared in b |
| 32 | diffs.push(new Diff(DIFF_EQUAL, b.slice(bCommon, bIndex))); |
| 33 | }; |
| 34 | |
| 35 | diffSequences(a.length, b.length, isCommon, foundSubsequence); |
| 36 | |
| 37 | // After the last common subsequence, push remaining change items. |
| 38 | if (aIndex !== a.length) { |
| 39 | diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex))); |
| 40 | } |
| 41 | if (bIndex !== b.length) { |
| 42 | diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex))); |
| 43 | } |
| 44 | |
| 45 | return diffs; |
| 46 | }; |
| 47 | |
| 48 | export default diffStrings; |