( a: string, b: string, options?: DiffOptions, )
| 15 | } |
| 16 | |
| 17 | function diffStrings( |
| 18 | a: string, |
| 19 | b: string, |
| 20 | options?: DiffOptions, |
| 21 | ): [Array<Diff>, boolean] { |
| 22 | const truncate = options?.truncateThreshold ?? false |
| 23 | const truncateThreshold = Math.max( |
| 24 | Math.floor(options?.truncateThreshold ?? 0), |
| 25 | 0, |
| 26 | ) |
| 27 | let aLength = a.length |
| 28 | let bLength = b.length |
| 29 | if (truncate) { |
| 30 | const aMultipleLines = a.includes('\n') |
| 31 | const bMultipleLines = b.includes('\n') |
| 32 | const aNewLineSymbol = getNewLineSymbol(a) |
| 33 | const bNewLineSymbol = getNewLineSymbol(b) |
| 34 | // multiple-lines string expects a newline to be appended at the end |
| 35 | const _a = aMultipleLines |
| 36 | ? `${a.split(aNewLineSymbol, truncateThreshold).join(aNewLineSymbol)}\n` |
| 37 | : a |
| 38 | const _b = bMultipleLines |
| 39 | ? `${b.split(bNewLineSymbol, truncateThreshold).join(bNewLineSymbol)}\n` |
| 40 | : b |
| 41 | aLength = _a.length |
| 42 | bLength = _b.length |
| 43 | } |
| 44 | const truncated = aLength !== a.length || bLength !== b.length |
| 45 | |
| 46 | const isCommon = (aIndex: number, bIndex: number) => a[aIndex] === b[bIndex] |
| 47 | |
| 48 | let aIndex = 0 |
| 49 | let bIndex = 0 |
| 50 | const diffs: Array<Diff> = [] |
| 51 | |
| 52 | const foundSubsequence = ( |
| 53 | nCommon: number, |
| 54 | aCommon: number, |
| 55 | bCommon: number, |
| 56 | ) => { |
| 57 | if (aIndex !== aCommon) { |
| 58 | diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex, aCommon))) |
| 59 | } |
| 60 | |
| 61 | if (bIndex !== bCommon) { |
| 62 | diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex, bCommon))) |
| 63 | } |
| 64 | |
| 65 | aIndex = aCommon + nCommon // number of characters compared in a |
| 66 | bIndex = bCommon + nCommon // number of characters compared in b |
| 67 | diffs.push(new Diff(DIFF_EQUAL, b.slice(bCommon, bIndex))) |
| 68 | } |
| 69 | |
| 70 | diffSequences(aLength, bLength, isCommon, foundSubsequence) |
| 71 | |
| 72 | // After the last common subsequence, push remaining change items. |
| 73 | if (aIndex !== aLength) { |
| 74 | diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex))) |
no test coverage detected