get-fixed.js 1.6 KB

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