diffUtil.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. export function findExpandedKeys() {
  2. let prev = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  3. let next = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  4. const prevLen = prev.length;
  5. const nextLen = next.length;
  6. if (Math.abs(prevLen - nextLen) !== 1) {
  7. return {
  8. add: false,
  9. key: null
  10. };
  11. }
  12. function find(shorter, longer) {
  13. const cache = new Map();
  14. shorter.forEach(key => {
  15. cache.set(key, true);
  16. });
  17. const keys = longer.filter(key => !cache.has(key));
  18. return keys.length === 1 ? keys[0] : null;
  19. }
  20. if (prevLen < nextLen) {
  21. return {
  22. add: true,
  23. key: find(prev, next)
  24. };
  25. }
  26. return {
  27. add: false,
  28. key: find(next, prev)
  29. };
  30. }
  31. export function getExpandRange(shorter, longer, key) {
  32. const shorterStartIndex = shorter.findIndex(item => item.key === key);
  33. const shorterEndNode = shorter[shorterStartIndex + 1];
  34. const longerStartIndex = longer.findIndex(item => item.key === key);
  35. if (shorterEndNode) {
  36. const longerEndIndex = longer.findIndex(item => item.key === shorterEndNode.key);
  37. return longer.slice(longerStartIndex + 1, longerEndIndex);
  38. }
  39. return longer.slice(longerStartIndex + 1);
  40. }