batchify.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 operations which need to be applied to the input in order to transform
  8. * it into the output. Can be used with strings or arrays.
  9. *
  10. * const input = Array.from( 'abc' );
  11. * const output = Array.from( 'xaby' );
  12. * const batch = batchify( diff( input, output ), output );
  13. *
  14. * batch.forEach( operation => {
  15. * if ( operation.type == 'INSERT' ) {
  16. * input.splice( operation.index, 0, ...operation.values );
  17. * } else if ( operation.type == 'DELETE' ) {
  18. * input.splice( operation.index, operation.howMany );
  19. * }
  20. * } );
  21. *
  22. * input.join( '' ) == output.join( '' ); // -> true
  23. *
  24. * @method utils.batchify
  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 operations (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 batchify( diff, output ) {
  31. const batch = [];
  32. let left = 0;
  33. let right = 0;
  34. let lastOperation;
  35. diff.forEach( change => {
  36. if ( change == 'EQUAL' ) {
  37. pushLast();
  38. left++;
  39. right++;
  40. } else if ( change == 'INSERT' ) {
  41. if ( isContinuationOf( 'INSERT' ) ) {
  42. lastOperation.values.push( output[ right ] );
  43. } else {
  44. pushLast();
  45. lastOperation = {
  46. type: 'INSERT',
  47. index: left,
  48. values: [ output[ right ] ]
  49. };
  50. }
  51. left++;
  52. right++;
  53. } else /* if ( change == 'DELETE' ) */ {
  54. if ( isContinuationOf( 'DELETE' ) ) {
  55. lastOperation.howMany++;
  56. } else {
  57. pushLast();
  58. lastOperation = {
  59. type: 'DELETE',
  60. index: left,
  61. howMany: 1
  62. };
  63. }
  64. }
  65. } );
  66. pushLast();
  67. return batch;
  68. function pushLast() {
  69. if ( lastOperation ) {
  70. batch.push( lastOperation );
  71. lastOperation = null;
  72. }
  73. }
  74. function isContinuationOf( expected ) {
  75. return lastOperation && lastOperation.type == expected;
  76. }
  77. }