comparearrays.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. /**
  6. * @module utils/comparearrays
  7. */
  8. /**
  9. * Compares how given arrays relate to each other. One array can be: same as another array, prefix of another array
  10. * or completely different. If arrays are different, first index at which they differ is returned. Otherwise,
  11. * a flag specifying the relation is returned. Flags are negative numbers, so whenever a number >= 0 is returned
  12. * it means that arrays differ.
  13. *
  14. * compareArrays( [ 0, 2 ], [ 0, 2 ] ); // 'same'
  15. * compareArrays( [ 0, 2 ], [ 0, 2, 1 ] ); // 'prefix'
  16. * compareArrays( [ 0, 2 ], [ 0 ] ); // 'extension'
  17. * compareArrays( [ 0, 2 ], [ 1, 2 ] ); // 0
  18. * compareArrays( [ 0, 2 ], [ 0, 1 ] ); // 1
  19. *
  20. * @param {Array} a Array that is compared.
  21. * @param {Array} b Array to compare with.
  22. * @returns {module:utils/comparearrays~ArrayRelation} How array `a` is related to `b`.
  23. */
  24. export default function compareArrays( a, b ) {
  25. const minLen = Math.min( a.length, b.length );
  26. for ( let i = 0; i < minLen; i++ ) {
  27. if ( a[ i ] != b[ i ] ) {
  28. // The arrays are different.
  29. return i;
  30. }
  31. }
  32. // Both arrays were same at all points.
  33. if ( a.length == b.length ) {
  34. // If their length is also same, they are the same.
  35. return 'same';
  36. } else if ( a.length < b.length ) {
  37. // Compared array is shorter so it is a prefix of the other array.
  38. return 'prefix';
  39. } else {
  40. // Compared array is longer so it is an extension of the other array.
  41. return 'extension';
  42. }
  43. }
  44. /**
  45. * @typedef {'extension'|'same'|'prefix'} module:utils/comparearrays~ArrayRelation
  46. */