difftochanges.js 2.0 KB

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