-
Notifications
You must be signed in to change notification settings - Fork 1
/
symbol.js
executable file
·64 lines (55 loc) · 1.31 KB
/
symbol.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"use strict";
function next() {
return "@@Symbol:" + String(Math.random()).slice(2);
}
function Symbol(desc) {
if (this instanceof Symbol) {
throw new TypeError("Symbol is not a constructor");
}
const code = next();
const sym = Object.create(Symbol.prototype, {
_desc: {
value: desc,
enumerable: false,
configurable: false,
writable: false,
},
_code: {
value: code,
enumerable: false,
configurable: false,
writable: false,
},
});
return sym;
}
Symbol.prototype.toString = function () {
return this._code;
};
let globalRegister = {};
Symbol.for = function (desc) {
return globalRegister[desc] || (globalRegister[desc] = Symbol(desc));
};
Symbol.keyFor = function (sym) {
if (!(sym instanceof Symbol)) {
throw new TypeError("keyfor is required Symbol param");
}
for (const key in globalRegister) {
if (Object.hasOwnProperty.call(globalRegister, key)) {
if (globalRegister[key] === sym) {
return key;
}
}
}
};
// demo
const symbol1 = Symbol("heihei");
const symbol4 = Symbol("heihei");
console.error(symbol1 === symbol4);
const symbol2 = Symbol.for("haha");
const symbol3 = Symbol.for("haha");
console.error(symbol2 === symbol3);
console.error(Symbol.keyFor(symbol3));
const a = 1,
b = 2;
let c = a + b;