8
0

difftochanges.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. import diff from '../src/diff';
  6. import diffToChanges from '../src/difftochanges';
  7. describe( 'diffToChanges', () => {
  8. describe( 'equal patterns', () => {
  9. testDiff( 0, '', '' );
  10. testDiff( 0, 'abc', 'abc' );
  11. } );
  12. describe( 'insertion', () => {
  13. testDiff( 1, '', 'abc' );
  14. testDiff( 1, 'abc', 'abcd' );
  15. testDiff( 1, 'abc', 'abcdef' );
  16. testDiff( 2, 'abc', 'xxabcyy' );
  17. testDiff( 2, 'abc', 'axxbyyc' );
  18. } );
  19. describe( 'deletion', () => {
  20. testDiff( 1, 'abc', '' );
  21. testDiff( 1, 'abc', 'ac' );
  22. testDiff( 1, 'abc', 'bc' );
  23. testDiff( 1, 'abc', 'ab' );
  24. testDiff( 1, 'abc', 'c' );
  25. testDiff( 2, 'abc', 'b' );
  26. } );
  27. describe( 'replacement', () => {
  28. testDiff( 2, 'abc', 'def' );
  29. testDiff( 2, 'abc', 'axc' );
  30. testDiff( 2, 'abc', 'axyc' );
  31. testDiff( 2, 'abc', 'xybc' );
  32. testDiff( 2, 'abc', 'abxy' );
  33. } );
  34. describe( 'various', () => {
  35. testDiff( 3, 'abc', 'xbccy' );
  36. testDiff( 2, 'abcdef', 'defabc' );
  37. testDiff( 4, 'abcdef', 'axxdeyyfz' );
  38. testDiff( 4, 'abcdef', 'xybzc' );
  39. testDiff( 5, 'abcdef', 'bdxfy' );
  40. } );
  41. it( 'works with arrays', () => {
  42. const input = Array.from( 'abc' );
  43. const output = Array.from( 'xaby' );
  44. const changes = diffToChanges( diff( input, output ), output );
  45. changes.forEach( change => {
  46. if ( change.type == 'insert' ) {
  47. input.splice( change.index, 0, ...change.values );
  48. } else if ( change.type == 'delete' ) {
  49. input.splice( change.index, change.howMany );
  50. }
  51. } );
  52. expect( input ).to.deep.equal( output );
  53. expect( changes ).to.have.lengthOf( 3 );
  54. } );
  55. function testDiff( expectedChangeNumber, oldStr, newStr ) {
  56. it( `${ oldStr } => ${ newStr }`, () => {
  57. const changes = diffToChanges( diff( oldStr, newStr ), newStr );
  58. const oldStrChars = Array.from( oldStr );
  59. changes.forEach( change => {
  60. if ( change.type == 'insert' ) {
  61. oldStrChars.splice( change.index, 0, ...change.values );
  62. } else if ( change.type == 'delete' ) {
  63. oldStrChars.splice( change.index, change.howMany );
  64. }
  65. } );
  66. expect( oldStrChars.join( '' ) ).to.equal( newStr );
  67. expect( changes ).to.have.lengthOf( expectedChangeNumber );
  68. } );
  69. }
  70. } );