|
| 1 | +import type { IDiffItem, ILcsAlgorithm } from '../src' |
| 2 | +import { DiffType, diff } from '../src' |
| 3 | + |
| 4 | +function test_diff_string( |
| 5 | + lcs: ILcsAlgorithm | undefined, |
| 6 | + equals?: ((x: string, y: string) => boolean) | undefined, |
| 7 | +): void { |
| 8 | + const test_case = (a: string, b: string, expected: number): void => { |
| 9 | + const actual: Array<IDiffItem<string>> = diff(a, b, { lcs, equals }) |
| 10 | + const left: string = actual |
| 11 | + .filter(x => x.type !== DiffType.ADDED) |
| 12 | + .map(x => x.tokens) |
| 13 | + .join('') |
| 14 | + const right: string = actual |
| 15 | + .filter(x => x.type !== DiffType.REMOVED) |
| 16 | + .map(x => x.tokens) |
| 17 | + .join('') |
| 18 | + expect(left).toEqual(a) |
| 19 | + expect(right).toEqual(b) |
| 20 | + |
| 21 | + const common: string = actual |
| 22 | + .filter(x => x.type === DiffType.COMMON) |
| 23 | + .map(x => x.tokens) |
| 24 | + .join('') |
| 25 | + expect(common.length).toEqual(expected) |
| 26 | + |
| 27 | + let i: number = 0 |
| 28 | + let j: number = 0 |
| 29 | + for (; i < common.length && j < a.length; ++i, ++j) { |
| 30 | + while (i < common.length && j < a.length && common[i] !== a[j]) j += 1 |
| 31 | + } |
| 32 | + expect(i).toEqual(common.length) |
| 33 | + } |
| 34 | + |
| 35 | + test_case('f8d1d155-d14e-433f-88e1-07b54f184740', 'a00322f7-256e-46fe-ae91-8de835c57778', 12) |
| 36 | + test_case('abcde', 'ace', 3) |
| 37 | + test_case('ace', 'abcde', 3) |
| 38 | + test_case('abc', 'abc', 3) |
| 39 | + test_case('abc', 'abce', 3) |
| 40 | + test_case('', 'abce', 0) |
| 41 | + test_case('abce', '', 0) |
| 42 | + test_case('', '', 0) |
| 43 | + test_case('123466786', '2347982352', 5) |
| 44 | + test_case('abeep boop', 'beep boob blah', 8) |
| 45 | + test_case('1234', '21234', 4) |
| 46 | + test_case('1234', '23414', 3) |
| 47 | + test_case('1234', '231234', 4) |
| 48 | + test_case('1234', '23131234', 4) |
| 49 | + test_case('1234', '2313123434', 4) |
| 50 | + test_case('23131234', '1234', 4) |
| 51 | +} |
| 52 | + |
| 53 | +describe('diff', () => { |
| 54 | + it('lcs_myers', async () => { |
| 55 | + test_diff_string('myers') |
| 56 | + |
| 57 | + const { lcs_myers } = await import('@algorithm.ts/lcs') |
| 58 | + test_diff_string(lcs_myers) |
| 59 | + }) |
| 60 | + |
| 61 | + it('lcs_myers_linear_space', async () => { |
| 62 | + test_diff_string('myers_linear_space') |
| 63 | + |
| 64 | + const { lcs_myers_linear_space } = await import('@algorithm.ts/lcs') |
| 65 | + test_diff_string(lcs_myers_linear_space) |
| 66 | + }) |
| 67 | + |
| 68 | + it('lcs_dp', async () => { |
| 69 | + test_diff_string('dp') |
| 70 | + |
| 71 | + const { lcs_dp } = await import('@algorithm.ts/lcs') |
| 72 | + test_diff_string(lcs_dp) |
| 73 | + }) |
| 74 | + |
| 75 | + it('default', async () => { |
| 76 | + test_diff_string(undefined) |
| 77 | + test_diff_string(undefined, (x, y) => x === y) |
| 78 | + }) |
| 79 | +}) |
0 commit comments