difftochanges.js 2.0 KB

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