/
hashKey.js
95 lines (83 loc) · 2.19 KB
/
hashKey.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
define(['lib/lodash'], function (_) {
var hashKey = function (v) {
var value = v,
uid = v;
if (v && (typeof v === 'object' || typeof v === 'function')) {
if (!me.get(v)) {
me.createHashKeysFor(v);
}
uid = v[me.hiddenKey];
}
return typeof v + '-' + uid;
}, me = hashKey;
me.hiddenKey = '__pojoVizKey__';
me.get = function (v) {
if (v.hasOwnProperty) {
return v.hasOwnProperty(me.hiddenKey) &&
v[me.hiddenKey];
}
return v[me.hiddenKey];
};
me.createHashKeysFor = function (obj) {
function localToString(obj) {
var match;
try {
match = obj.toString().match(/^\[object (\S*?)\]/);
} catch (e) {
match = false;
}
return match && match[1];
}
function hasAClassName(obj) {
var match = localToString(obj);
if (match === 'Object') {
return obj === Object.prototype && 'Object';
}
return match;
}
function getName(obj) {
var name, className;
if (obj.hasOwnProperty &&
obj.hasOwnProperty(me.hiddenKey)) {
return obj[me.hiddenKey];
}
name = obj.hasOwnProperty &&
obj.hasOwnProperty('name') &&
typeof obj.name === 'string' &&
obj.name;
className = hasAClassName(obj);
if (!name && className) {
name = className;
}
name = name || _.uniqueId();
name = name.replace(/[\. ]/g, '-');
return name;
}
// if the obj is a prototype then try to analyze
// the constructor first so that the prototype becomes
// [name].prototype
if (obj.hasOwnProperty &&
obj.hasOwnProperty('constructor')) {
me.createHashKeysFor(obj.constructor);
} else {
me.set(obj, getName(obj));
if (obj.hasOwnProperty &&
obj.hasOwnProperty('prototype')) {
me.set(obj.prototype, getName(obj) + '-prototype');
}
}
};
me.set = function (obj, key) {
if (typeof key !== 'string') {
throw 'The key needs to be a string';
}
if (!me.get(obj)) {
Object.defineProperty(obj, me.hiddenKey, {
value: key
});
}
return me;
};
window.hashKey = hashKey;
return me;
});