/
difftochanges.ts
114 lines (100 loc) · 2.67 KB
/
difftochanges.ts
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
import type { DiffResult } from './diff.js';
/**
* @module utils/difftochanges
*/
/**
* Creates a set of changes which need to be applied to the input in order to transform
* it into the output. This function can be used with strings or arrays.
*
* ```ts
* const input = Array.from( 'abc' );
* const output = Array.from( 'xaby' );
* const changes = diffToChanges( diff( input, output ), output );
*
* changes.forEach( change => {
* if ( change.type == 'insert' ) {
* input.splice( change.index, 0, ...change.values );
* } else if ( change.type == 'delete' ) {
* input.splice( change.index, change.howMany );
* }
* } );
*
* input.join( '' ) == output.join( '' ); // -> true
* ```
*
* @typeParam T The type of output array element.
* @param diff Result of {@link module:utils/diff~diff}.
* @param output The string or array which was passed as diff's output.
* @returns Set of changes (insert or delete) which need to be applied to the input
* in order to transform it into the output.
*/
export default function diffToChanges<T>( diff: ReadonlyArray<DiffResult>, output: ArrayLike<T> ): Array<Change<T>> {
const changes: Array<Change<T>> = [];
let index = 0;
let lastOperation: Change<T> | null = null;
diff.forEach( change => {
if ( change == 'equal' ) {
pushLast();
index++;
} else if ( change == 'insert' ) {
if ( lastOperation && lastOperation.type == 'insert' ) {
lastOperation.values.push( output[ index ] );
} else {
pushLast();
lastOperation = {
type: 'insert',
index,
values: [ output[ index ] ]
};
}
index++;
} else /* if ( change == 'delete' ) */ {
if ( lastOperation && lastOperation.type == 'delete' ) {
lastOperation.howMany++;
} else {
pushLast();
lastOperation = {
type: 'delete',
index,
howMany: 1
};
}
}
} );
pushLast();
return changes;
function pushLast() {
if ( lastOperation ) {
changes.push( lastOperation );
lastOperation = null;
}
}
}
/**
* An object describing insertion change.
*
* @typeParam T The type of output array element.
*/
export interface InsertChange<T> {
type: 'insert';
index: number;
values: Array<T>;
}
/**
* An object describing deletion change.
*/
export interface DeleteChange {
type: 'delete';
index: number;
howMany: number;
}
/**
* The element of the result of {@link module:utils/difftochanges~diffToChanges} function.
*
* @typeParam T The type of output array element.
*/
export type Change<T> = InsertChange<T> | DeleteChange;