NameMap.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
  2. import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
  3. import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
  4. import _createClass from "@babel/runtime/helpers/esm/createClass";
  5. import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
  6. import _typeof from "@babel/runtime/helpers/esm/typeof";
  7. var SPLIT = '__@field_split__';
  8. /**
  9. * Convert name path into string to fast the fetch speed of Map.
  10. */
  11. function normalize(namePath) {
  12. return namePath.map(function (cell) {
  13. return "".concat(_typeof(cell), ":").concat(cell);
  14. })
  15. // Magic split
  16. .join(SPLIT);
  17. }
  18. /**
  19. * NameMap like a `Map` but accepts `string[]` as key.
  20. */
  21. var NameMap = /*#__PURE__*/function () {
  22. function NameMap() {
  23. _classCallCheck(this, NameMap);
  24. _defineProperty(this, "kvs", new Map());
  25. }
  26. _createClass(NameMap, [{
  27. key: "set",
  28. value: function set(key, value) {
  29. this.kvs.set(normalize(key), value);
  30. }
  31. }, {
  32. key: "get",
  33. value: function get(key) {
  34. return this.kvs.get(normalize(key));
  35. }
  36. }, {
  37. key: "update",
  38. value: function update(key, updater) {
  39. var origin = this.get(key);
  40. var next = updater(origin);
  41. if (!next) {
  42. this.delete(key);
  43. } else {
  44. this.set(key, next);
  45. }
  46. }
  47. }, {
  48. key: "delete",
  49. value: function _delete(key) {
  50. this.kvs.delete(normalize(key));
  51. }
  52. // Since we only use this in test, let simply realize this
  53. }, {
  54. key: "map",
  55. value: function map(callback) {
  56. return _toConsumableArray(this.kvs.entries()).map(function (_ref) {
  57. var _ref2 = _slicedToArray(_ref, 2),
  58. key = _ref2[0],
  59. value = _ref2[1];
  60. var cells = key.split(SPLIT);
  61. return callback({
  62. key: cells.map(function (cell) {
  63. var _cell$match = cell.match(/^([^:]*):(.*)$/),
  64. _cell$match2 = _slicedToArray(_cell$match, 3),
  65. type = _cell$match2[1],
  66. unit = _cell$match2[2];
  67. return type === 'number' ? Number(unit) : unit;
  68. }),
  69. value: value
  70. });
  71. });
  72. }
  73. }, {
  74. key: "toJSON",
  75. value: function toJSON() {
  76. var json = {};
  77. this.map(function (_ref3) {
  78. var key = _ref3.key,
  79. value = _ref3.value;
  80. json[key.join('.')] = value;
  81. return null;
  82. });
  83. return json;
  84. }
  85. }]);
  86. return NameMap;
  87. }();
  88. export default NameMap;