utils/fastdiff
@ckeditor/ckeditor5-utils/src/fastdiff
module
Filtering
Functions
-
fastDiff( oldText, newText ) → Array
static
Finds position of the first and last change in the given strings and generates set of changes. Set of changes can be applied to the input text in order to transform it into the output text, for example:
fastDiff( '12a', '12xyza' ); // [ { index: 2, type: 'insert', values: [ 'x', 'y', 'z' ] } ] fastDiff( '12a', '12aa' ); // [ { index: 3, type: 'insert', values: [ 'a' ] } ] fastDiff( '12xyza', '12a' ); // [ { index: 2, type: 'delete', howMany: 3 } ] fastDiff( '12aa', '12a' ); // [ { index: 3, type: 'delete', howMany: 1 } ] fastDiff( '12abc3', '2ab' ); // [ { index: 0, type: 'insert', values: [ '2', 'a', 'b' ] }, { index: 3, type: 'delete', howMany: 6 } ]
Using returned results you can modify
oldText
to transform it intonewText
:let input = '12abc3'; const output = '2ab'; const changes = fastDiff( input, output ); changes.forEach( change => { if ( change.type == 'insert' ) { input = input.substring( 0, change.index ) + change.values.join( '' ) + input.substring( change.index ); } else if ( change.type == 'delete' ) { input = input.substring( 0, change.index ) + input.substring( change.index + change.howMany ); } } ); input === output; // -> true
The output format of this function is compatible with
diffToChanges
output format.Parameters
oldText : String
Input string.
newText : String
Input string.
Returns
Array
Array of changes.