difftochanges.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module utils/difftochanges
  7. */
  8. /**
  9. * Creates a set of changes which need to be applied to the input in order to transform
  10. * it into the output. This function can be used with strings or arrays.
  11. *
  12. * const input = Array.from( 'abc' );
  13. * const output = Array.from( 'xaby' );
  14. * const changes = diffToChanges( diff( input, output ), output );
  15. *
  16. * changes.forEach( change => {
  17. * if ( change.type == 'insert' ) {
  18. * input.splice( change.index, 0, ...change.values );
  19. * } else if ( change.type == 'delete' ) {
  20. * input.splice( change.index, change.howMany );
  21. * }
  22. * } );
  23. *
  24. * input.join( '' ) == output.join( '' ); // -> true
  25. *
  26. * @param {Array.<'equal'|'insert'|'delete'>} diff Result of {@link module:utils/diff~diff}.
  27. * @param {String|Array} output The string or array which was passed as diff's output.
  28. * @returns {Array.<Object>} Set of changes (insert or delete) which need to be applied to the input
  29. * in order to transform it into the output.
  30. */
  31. export default function diffToChanges( diff, output ) {
  32. const changes = [];
  33. let index = 0;
  34. let lastOperation;
  35. diff.forEach( change => {
  36. if ( change == 'equal' ) {
  37. pushLast();
  38. index++;
  39. } else if ( change == 'insert' ) {
  40. if ( isContinuationOf( 'insert' ) ) {
  41. lastOperation.values.push( output[ index ] );
  42. } else {
  43. pushLast();
  44. lastOperation = {
  45. type: 'insert',
  46. index,
  47. values: [ output[ index ] ]
  48. };
  49. }
  50. index++;
  51. } else /* if ( change == 'delete' ) */ {
  52. if ( isContinuationOf( 'delete' ) ) {
  53. lastOperation.howMany++;
  54. } else {
  55. pushLast();
  56. lastOperation = {
  57. type: 'delete',
  58. index,
  59. howMany: 1
  60. };
  61. }
  62. }
  63. } );
  64. pushLast();
  65. return changes;
  66. function pushLast() {
  67. if ( lastOperation ) {
  68. changes.push( lastOperation );
  69. lastOperation = null;
  70. }
  71. }
  72. function isContinuationOf( expected ) {
  73. return lastOperation && lastOperation.type == expected;
  74. }
  75. }