-
Notifications
You must be signed in to change notification settings - Fork 0
/
excercise.js
101 lines (87 loc) · 2.6 KB
/
excercise.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
96
97
98
99
100
var thresholdCounter = (function () {
var instance;
var thresholds;
var counters;
function createInstance() {
thresholds = new Map();
counters = new Map();
instance = new Object();
instance.getCounter = getCounter;
instance.incCounter = incCounter;
instance.getThreshold = getThreshold;
instance.setThreshold = setThreshold;
return instance;
}
function getCounter(obj) {
var counter = counters.get(obj);
if (typeof counter === 'undefined') {
counters.set(obj, 0);
}
return counters.get(obj);
}
function incCounter(obj) {
var count = getCounter(obj);
counters.set(obj, ++count);
}
function getThreshold(obj) {
var threshold = thresholds.get(obj);
if (typeof threshold === 'undefined') {
thresholds.set(obj, Number.MAX_SAFE_INTEGER);
}
return thresholds.get(obj);
}
function setThreshold(obj, threshold) {
thresholds.set(obj, threshold);
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
var copier = (function () {
function innerCopy(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
copy.getThreshold = function() {
return thresholdCounter.getInstance().getThreshold(obj);
}
copy.getNumOfCopies = function () {
return thresholdCounter.getInstance().getCounter(obj);
}
return copy;
}
return {
copy: function (obj) {
var threshold = thresholdCounter.getInstance().getThreshold(obj);
if (typeof threshold === 'undefined') {
return null;
}
var counter = thresholdCounter.getInstance().getCounter(obj);
if (counter === threshold) {
throw "threshold exceeded";
} else {
thresholdCounter.getInstance().incCounter(obj);
return innerCopy(obj);
}
}
};
})();
var obj1 = {type:"Fiat", model:"500", color:"white"};
thresholdCounter.getInstance().setThreshold(obj1, 2);
var obj2 = copier.copy(obj1);
console.log(obj2.getThreshold());
console.log(obj2.getNumOfCopies());
var obj3 = copier.copy(obj1);
console.log(obj2.getNumOfCopies());
var obj4 = copier.copy(obj1);
console.log(obj2.getNumOfCopies());
console.log(obj4 === null);
var someOtherObj1 = copier.copy(obj2);
console.log(someOtherObj1 === null);