algorithmUtil.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.findListDiffIndex = findListDiffIndex;
  6. exports.getIndexByStartLoc = getIndexByStartLoc;
  7. /**
  8. * Get index with specific start index one by one. e.g.
  9. * min: 3, max: 9, start: 6
  10. *
  11. * Return index is:
  12. * [0]: 6
  13. * [1]: 7
  14. * [2]: 5
  15. * [3]: 8
  16. * [4]: 4
  17. * [5]: 9
  18. * [6]: 3
  19. */
  20. function getIndexByStartLoc(min, max, start, index) {
  21. const beforeCount = start - min;
  22. const afterCount = max - start;
  23. const balanceCount = Math.min(beforeCount, afterCount) * 2;
  24. // Balance
  25. if (index <= balanceCount) {
  26. const stepIndex = Math.floor(index / 2);
  27. if (index % 2) {
  28. return start + stepIndex + 1;
  29. }
  30. return start - stepIndex;
  31. }
  32. // One is out of range
  33. if (beforeCount > afterCount) {
  34. return start - (index - afterCount);
  35. }
  36. return start + (index - beforeCount);
  37. }
  38. /**
  39. * We assume that 2 list has only 1 item diff and others keeping the order.
  40. * So we can use dichotomy algorithm to find changed one.
  41. */
  42. function findListDiffIndex(originList, targetList, getKey) {
  43. const originLen = originList.length;
  44. const targetLen = targetList.length;
  45. let shortList;
  46. let longList;
  47. if (originLen === 0 && targetLen === 0) {
  48. return null;
  49. }
  50. if (originLen < targetLen) {
  51. shortList = originList;
  52. longList = targetList;
  53. } else {
  54. shortList = targetList;
  55. longList = originList;
  56. }
  57. const notExistKey = {
  58. __EMPTY_ITEM__: true
  59. };
  60. function getItemKey(item) {
  61. if (item !== undefined) {
  62. return getKey(item);
  63. }
  64. return notExistKey;
  65. }
  66. // Loop to find diff one
  67. let diffIndex = null;
  68. let multiple = Math.abs(originLen - targetLen) !== 1;
  69. for (let i = 0; i < longList.length; i += 1) {
  70. const shortKey = getItemKey(shortList[i]);
  71. const longKey = getItemKey(longList[i]);
  72. if (shortKey !== longKey) {
  73. diffIndex = i;
  74. multiple = multiple || shortKey !== getItemKey(longList[i + 1]);
  75. break;
  76. }
  77. }
  78. return diffIndex === null ? null : {
  79. index: diffIndex,
  80. multiple
  81. };
  82. }