get.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* eslint max-statements: 0 */
  2. "use strict";
  3. var indexOf = require("es5-ext/array/#/e-index-of");
  4. var create = Object.create;
  5. module.exports = function () {
  6. var lastId = 0, map = [], cache = create(null);
  7. return {
  8. get: function (args) {
  9. var index = 0, set = map, i, length = args.length;
  10. if (length === 0) return set[length] || null;
  11. if ((set = set[length])) {
  12. while (index < length - 1) {
  13. i = indexOf.call(set[0], args[index]);
  14. if (i === -1) return null;
  15. set = set[1][i];
  16. ++index;
  17. }
  18. i = indexOf.call(set[0], args[index]);
  19. if (i === -1) return null;
  20. return set[1][i] || null;
  21. }
  22. return null;
  23. },
  24. set: function (args) {
  25. var index = 0, set = map, i, length = args.length;
  26. if (length === 0) {
  27. set[length] = ++lastId;
  28. } else {
  29. if (!set[length]) {
  30. set[length] = [[], []];
  31. }
  32. set = set[length];
  33. while (index < length - 1) {
  34. i = indexOf.call(set[0], args[index]);
  35. if (i === -1) {
  36. i = set[0].push(args[index]) - 1;
  37. set[1].push([[], []]);
  38. }
  39. set = set[1][i];
  40. ++index;
  41. }
  42. i = indexOf.call(set[0], args[index]);
  43. if (i === -1) {
  44. i = set[0].push(args[index]) - 1;
  45. }
  46. set[1][i] = ++lastId;
  47. }
  48. cache[lastId] = args;
  49. return lastId;
  50. },
  51. delete: function (id) {
  52. var index = 0, set = map, i, args = cache[id], length = args.length, path = [];
  53. if (length === 0) {
  54. delete set[length];
  55. } else if ((set = set[length])) {
  56. while (index < length - 1) {
  57. i = indexOf.call(set[0], args[index]);
  58. if (i === -1) {
  59. return;
  60. }
  61. path.push(set, i);
  62. set = set[1][i];
  63. ++index;
  64. }
  65. i = indexOf.call(set[0], args[index]);
  66. if (i === -1) {
  67. return;
  68. }
  69. id = set[1][i];
  70. set[0].splice(i, 1);
  71. set[1].splice(i, 1);
  72. while (!set[0].length && path.length) {
  73. i = path.pop();
  74. set = path.pop();
  75. set[0].splice(i, 1);
  76. set[1].splice(i, 1);
  77. }
  78. }
  79. delete cache[id];
  80. },
  81. clear: function () {
  82. map = [];
  83. cache = create(null);
  84. }
  85. };
  86. };