This repository has been archived by the owner on Jun 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdifftochanges.js
86 lines (75 loc) · 2.08 KB
/
difftochanges.js
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
/**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @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.
*
* 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
*
* @param {Array.<'equal'|'insert'|'delete'>} diff Result of {@link module:utils/diff~diff}.
* @param {String|Array} output The string or array which was passed as diff's output.
* @returns {Array.<Object>} 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( diff, output ) {
const changes = [];
let index = 0;
let lastOperation;
diff.forEach( change => {
if ( change == 'equal' ) {
pushLast();
index++;
} else if ( change == 'insert' ) {
if ( isContinuationOf( 'insert' ) ) {
lastOperation.values.push( output[ index ] );
} else {
pushLast();
lastOperation = {
type: 'insert',
index,
values: [ output[ index ] ]
};
}
index++;
} else /* if ( change == 'delete' ) */ {
if ( isContinuationOf( 'delete' ) ) {
lastOperation.howMany++;
} else {
pushLast();
lastOperation = {
type: 'delete',
index,
howMany: 1
};
}
}
} );
pushLast();
return changes;
function pushLast() {
if ( lastOperation ) {
changes.push( lastOperation );
lastOperation = null;
}
}
function isContinuationOf( expected ) {
return lastOperation && lastOperation.type == expected;
}
}