nest.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. var zrUtil = require("zrender/lib/core/util");
  2. /**
  3. * nest helper used to group by the array.
  4. * can specified the keys and sort the keys.
  5. */
  6. function nest() {
  7. var keysFunction = [];
  8. var sortKeysFunction = [];
  9. /**
  10. * map an Array into the mapObject.
  11. * @param {Array} array
  12. * @param {number} depth
  13. */
  14. function map(array, depth) {
  15. if (depth >= keysFunction.length) {
  16. return array;
  17. }
  18. var i = -1;
  19. var n = array.length;
  20. var keyFunction = keysFunction[depth++];
  21. var mapObject = {};
  22. var valuesByKey = {};
  23. while (++i < n) {
  24. var keyValue = keyFunction(array[i]);
  25. var values = valuesByKey[keyValue];
  26. if (values) {
  27. values.push(array[i]);
  28. } else {
  29. valuesByKey[keyValue] = [array[i]];
  30. }
  31. }
  32. zrUtil.each(valuesByKey, function (value, key) {
  33. mapObject[key] = map(value, depth);
  34. });
  35. return mapObject;
  36. }
  37. /**
  38. * transform the Map Object to multidimensional Array
  39. * @param {Object} map
  40. * @param {number} depth
  41. */
  42. function entriesMap(mapObject, depth) {
  43. if (depth >= keysFunction.length) {
  44. return mapObject;
  45. }
  46. var array = [];
  47. var sortKeyFunction = sortKeysFunction[depth++];
  48. zrUtil.each(mapObject, function (value, key) {
  49. array.push({
  50. key: key,
  51. values: entriesMap(value, depth)
  52. });
  53. });
  54. if (sortKeyFunction) {
  55. return array.sort(function (a, b) {
  56. return sortKeyFunction(a.key, b.key);
  57. });
  58. } else {
  59. return array;
  60. }
  61. }
  62. return {
  63. /**
  64. * specified the key to groupby the arrays.
  65. * users can specified one more keys.
  66. * @param {Function} d
  67. */
  68. key: function (d) {
  69. keysFunction.push(d);
  70. return this;
  71. },
  72. /**
  73. * specified the comparator to sort the keys
  74. * @param {Function} order
  75. */
  76. sortKeys: function (order) {
  77. sortKeysFunction[keysFunction.length - 1] = order;
  78. return this;
  79. },
  80. /**
  81. * the array to be grouped by.
  82. * @param {Array} array
  83. */
  84. entries: function (array) {
  85. return entriesMap(map(array, 0), 0);
  86. }
  87. };
  88. }
  89. module.exports = nest;