index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. var defineProperty = Object.defineProperty;
  5. function next() {
  6. return "@@symbol:" + String(Math.random()).slice(2);
  7. }
  8. function Symbol(desc) {
  9. if (!(this instanceof Symbol)) {
  10. return new Symbol(desc);
  11. }
  12. var _symbol = this._symbol = next();
  13. defineProperty(this, '_desc', {
  14. value: desc,
  15. enumerable: false,
  16. writable: false,
  17. configurable: false
  18. });
  19. defineProperty(Object.prototype, _symbol, {
  20. set: function(value) {
  21. defineProperty(this, _symbol, {
  22. value: value,
  23. enumerable: false,
  24. writable: true
  25. });
  26. }
  27. });
  28. }
  29. Symbol.prototype.toString = function toString() {
  30. return this._symbol;
  31. };
  32. var globalSymbolRegistry = {};
  33. Symbol.for = function symbolFor(key) {
  34. key = String(key);
  35. return globalSymbolRegistry[key] || (globalSymbolRegistry[key] = Symbol(key));
  36. };
  37. Symbol.keyFor = function keyFor(sym) {
  38. if (!(sym instanceof Symbol)) {
  39. throw new TypeError("Symbol.keyFor requires a Symbol argument");
  40. }
  41. for (var key in globalSymbolRegistry) {
  42. if (globalSymbolRegistry[key] === sym) {
  43. return key;
  44. }
  45. }
  46. return undefined;
  47. };
  48. module.exports = this.Symbol || Symbol;