Source: ListDiffer.ts

  1. /*
  2. egjs-list-differ
  3. Copyright (c) 2019-present NAVER Corp.
  4. MIT license
  5. */
  6. import { DiffResult, ListFormat } from "./types";
  7. import { diff } from "./utils";
  8. /**
  9. * A module that checks diff when values are added, removed, or changed in an array.
  10. * @ko 배열 또는 오브젝트에서 값이 추가되거나 삭제되거나 순서가 변경사항을 체크하는 모듈입니다.
  11. * @memberof eg
  12. */
  13. class ListDiffer<T> {
  14. private list: T[];
  15. /**
  16. * @param - Initializing Data Array. <ko> 초기 설정할 데이터 배열.</ko>
  17. * @param - This callback function returns the key of the item. <ko> 아이템의 키를 반환하는 콜백 함수입니다.</ko>
  18. * @example
  19. * import ListDiffer from "@egjs/list-differ";
  20. * // script => eg.ListDiffer
  21. * const differ = new ListDiffer([0, 1, 2, 3, 4, 5], e => e);
  22. * const result = differ.update([7, 8, 0, 4, 3, 6, 2, 1]);
  23. * // List before update
  24. * // [1, 2, 3, 4, 5]
  25. * console.log(result.prevList);
  26. * // Updated list
  27. * // [4, 3, 6, 2, 1]
  28. * console.log(result.list);
  29. * // Index array of values added to `list`.
  30. * // [0, 1, 5]
  31. * console.log(result.added);
  32. * // Index array of values removed in `prevList`.
  33. * // [5]
  34. * console.log(result.removed);
  35. * // An array of index pairs of `prevList` and `list` with different indexes from `prevList` and `list`.
  36. * // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
  37. * console.log(result.changed);
  38. * // The subset of `changed` and an array of index pairs that moved data directly. Indicate an array of absolute index pairs of `ordered`.(Formatted by: Array<[index of prevList, index of list]>)
  39. * // [[4, 3], [3, 4], [2, 6]]
  40. * console.log(result.pureChanged);
  41. * // An array of index pairs to be `ordered` that can synchronize `list` before adding data. (Formatted by: Array<[prevIndex, nextIndex]>)
  42. * // [[4, 1], [4, 2], [4, 3]]
  43. * console.log(result.ordered);
  44. * // An array of index pairs of `prevList` and `list` that have not been added/removed so data is preserved.
  45. * // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
  46. * console.log(result.maintained);
  47. */
  48. constructor(
  49. list: ListFormat<T> = [],
  50. private findKeyCallback?: (e: T, i: number, arr: T[]) => number | string,
  51. ) {
  52. this.list = [].slice.call(list);
  53. }
  54. /**
  55. * Update list.
  56. * @ko 리스트를 업데이트를 합니다.
  57. * @param - List to update <ko> 업데이트할 리스트 </ko>
  58. * @return - Returns the results of an update from `prevList` to `list`.<ko> `prevList`에서 `list`로 업데이트한 결과를 반환한다. </ko>
  59. */
  60. public update(list: ListFormat<T>): DiffResult<T> {
  61. const newData: T[] = [].slice.call(list);
  62. const result = diff<T>(this.list, newData, this.findKeyCallback);
  63. this.list = newData;
  64. return result;
  65. }
  66. }
  67. export default ListDiffer;
comments powered by Disqus