difftochanges.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  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. * @method utils.diffToChanges
  27. * @param {Array.<'equal'|'insert'|'delete'>} diff Result of {@link utils.diff}.
  28. * @param {String|Array} output The string or array which was passed as diff's output.
  29. * @returns {Array.<Object>} Set of changes (insert or delete) which need to be applied to the input
  30. * in order to transform it into the output.
  31. */
  32. export default function diffToChanges( diff, output ) {
  33. const changes = [];
  34. let index = 0;
  35. let lastOperation;
  36. diff.forEach( change => {
  37. if ( change == 'equal' ) {
  38. pushLast();
  39. index++;
  40. } else if ( change == 'insert' ) {
  41. if ( isContinuationOf( 'insert' ) ) {
  42. lastOperation.values.push( output[ index ] );
  43. } else {
  44. pushLast();
  45. lastOperation = {
  46. type: 'insert',
  47. index: index,
  48. values: [ output[ index ] ]
  49. };
  50. }
  51. index++;
  52. } else /* if ( change == 'delete' ) */ {
  53. if ( isContinuationOf( 'delete' ) ) {
  54. lastOperation.howMany++;
  55. } else {
  56. pushLast();
  57. lastOperation = {
  58. type: 'delete',
  59. index: index,
  60. howMany: 1
  61. };
  62. }
  63. }
  64. } );
  65. pushLast();
  66. return changes;
  67. function pushLast() {
  68. if ( lastOperation ) {
  69. changes.push( lastOperation );
  70. lastOperation = null;
  71. }
  72. }
  73. function isContinuationOf( expected ) {
  74. return lastOperation && lastOperation.type == expected;
  75. }
  76. }