1 | var NATIVE_WEAK_MAP = require('../internals/native-weak-map');
|
---|
2 | var global = require('../internals/global');
|
---|
3 | var isObject = require('../internals/is-object');
|
---|
4 | var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
|
---|
5 | var objectHas = require('../internals/has');
|
---|
6 | var shared = require('../internals/shared-store');
|
---|
7 | var sharedKey = require('../internals/shared-key');
|
---|
8 | var hiddenKeys = require('../internals/hidden-keys');
|
---|
9 |
|
---|
10 | var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
|
---|
11 | var WeakMap = global.WeakMap;
|
---|
12 | var set, get, has;
|
---|
13 |
|
---|
14 | var enforce = function (it) {
|
---|
15 | return has(it) ? get(it) : set(it, {});
|
---|
16 | };
|
---|
17 |
|
---|
18 | var getterFor = function (TYPE) {
|
---|
19 | return function (it) {
|
---|
20 | var state;
|
---|
21 | if (!isObject(it) || (state = get(it)).type !== TYPE) {
|
---|
22 | throw TypeError('Incompatible receiver, ' + TYPE + ' required');
|
---|
23 | } return state;
|
---|
24 | };
|
---|
25 | };
|
---|
26 |
|
---|
27 | if (NATIVE_WEAK_MAP || shared.state) {
|
---|
28 | var store = shared.state || (shared.state = new WeakMap());
|
---|
29 | var wmget = store.get;
|
---|
30 | var wmhas = store.has;
|
---|
31 | var wmset = store.set;
|
---|
32 | set = function (it, metadata) {
|
---|
33 | if (wmhas.call(store, it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
|
---|
34 | metadata.facade = it;
|
---|
35 | wmset.call(store, it, metadata);
|
---|
36 | return metadata;
|
---|
37 | };
|
---|
38 | get = function (it) {
|
---|
39 | return wmget.call(store, it) || {};
|
---|
40 | };
|
---|
41 | has = function (it) {
|
---|
42 | return wmhas.call(store, it);
|
---|
43 | };
|
---|
44 | } else {
|
---|
45 | var STATE = sharedKey('state');
|
---|
46 | hiddenKeys[STATE] = true;
|
---|
47 | set = function (it, metadata) {
|
---|
48 | if (objectHas(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
|
---|
49 | metadata.facade = it;
|
---|
50 | createNonEnumerableProperty(it, STATE, metadata);
|
---|
51 | return metadata;
|
---|
52 | };
|
---|
53 | get = function (it) {
|
---|
54 | return objectHas(it, STATE) ? it[STATE] : {};
|
---|
55 | };
|
---|
56 | has = function (it) {
|
---|
57 | return objectHas(it, STATE);
|
---|
58 | };
|
---|
59 | }
|
---|
60 |
|
---|
61 | module.exports = {
|
---|
62 | set: set,
|
---|
63 | get: get,
|
---|
64 | has: has,
|
---|
65 | enforce: enforce,
|
---|
66 | getterFor: getterFor
|
---|
67 | };
|
---|