-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
273 lines (273 loc) · 10 KB
/
index.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isInstanceOf = exports.defineProperties = exports.bases = void 0;
const tslib_1 = require("tslib");
// @ts-ignore
const flatMap = tslib_1.__importStar(require("array.prototype.flatmap"));
// @ts-ignore
const ownKeys = tslib_1.__importStar(require("reflect.ownkeys"));
if (typeof Reflect.ownKeys === "undefined") {
ownKeys.shim();
}
if (typeof Array.prototype.flatMap === "undefined") {
flatMap.shim();
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function extendStatics(derived, base) {
for (const p of Reflect.ownKeys(base)) {
if (p === "length" || p === "prototype" || p === "name") {
continue;
}
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(base, p)) {
derived[p] = base[p];
}
}
}
function setPrototypeToProxy(self, baseClasses) {
const proto = {};
for (let i = baseClasses.length - 1; i >= 0; i--) {
const basePrototype = baseClasses[i].prototype;
extendStatics(self, baseClasses[i]);
for (const nextKey of Reflect.ownKeys(basePrototype)) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(basePrototype, nextKey)) {
const val = basePrototype[nextKey];
// Only transfer functions
if (nextKey !== "constructor" && typeof val === "function") {
// Make sure that the function is only called on the specific base.
// @ts-ignore
proto[nextKey] = function (...args) {
return val.apply(this.bases[i], args);
};
}
}
}
}
proto.constructor = self;
Object.freeze(proto);
self.prototype = proto;
return self;
}
/**
* Returns a class which when "inherits" from all of the base classes.
*
* This function isolates the method calls on the bases, so if any of the 2 bases share a property or method with the same name then, they will not affect each other.
*
* When you access a property or method directly on `this` and not on `this.bases`, and it doesn't exist on the `this` instance, then the first base class with the method/property will be the one given precedence and its method/property will be the one executed.
*
* The returned class must be initialized with the <i><b>instances</b></i> of each of the respective base classes
*
* Note: There is a caveat in setting properties, if you directly set a property in the constructor and the super class has the same property name then it will be overwritten, and the super class will refer to the same property, and things may break.
* This is not due to this library, this is due to the inherent dynamic nature of JavaScript.
* But, this library isolates the derived and base classes, ie prevents collision of their properties and methods.
* Thus, this problem can be avoided by using the <code>defineProperties</code> method from this library, if you use the <code>bases</code> methods as well.
* @param baseClasses The base classes to be inherited.
* @return A constructor taking in the *instances* of the base classes.
*
* @example
* class Activatable {
* val: boolean;
*
* constructor (val: boolean) {
* this.val = val;
* }
*
* activate () {
* this.val = true;
* }
*
* deactivate () {
* this.val = false;
* }
*
* get (): boolean {
* return this.val;
* }
* }
*
* class Accumulator {
* val: number;
*
* constructor (result: number) {
* this.val = result;
* }
*
* add (val: number) {
* this.val += val;
* }
*
* get (): number {
* return this.val;
* }
* }
*
* // Now let’s declare a new class inheriting from both of the classes:
* class NewClass extends bases(Activatable, Accumulator) {
* constructor () {
* // To initialize the bases create a new instance of them and pass them to the constructor of the super class, now you will no longer need the `super` keyword.
* super(
* new Activatable(true),
* new Accumulator(0),
* );
* }
*
* getBoth () {
* // To get a specific base use `this.base[index]` where index is the index of the base as given in the bases function.
* return `Gotten: ${this.bases[0].get()} ${this.bases[1].get()}`
* }
* }
*
* const n = new NewClass();
* console.log(n.val); // true: The base given first is given preference.
* console.log(n.get()); // true: The base given first is given preference, of course.
* n.add(10);
* n.deactivate();
* console.log(n.val, n.bases[1].val); // false 10: The bases are isolated, one can't affect the other, not directly that is.
*/
function bases(...baseClasses) {
function Self(...baseInstances) {
Reflect.defineProperty(this, 'bases', {
configurable: false,
enumerable: false,
value: baseInstances,
writable: false,
});
return new Proxy(this, {
isExtensible(target) {
return Reflect.isExtensible(target) && baseInstances.every(Reflect.isExtensible);
},
preventExtensions(target) {
return Reflect.preventExtensions(target) && baseInstances.every(Reflect.preventExtensions);
},
getOwnPropertyDescriptor(target, p) {
let pd = Reflect.getOwnPropertyDescriptor(target, p);
for (const base of baseInstances) {
if (pd != null) {
break;
}
pd = Reflect.getOwnPropertyDescriptor(base, p);
}
return pd;
},
has(target, p) {
return Reflect.has(target, p) || baseInstances.some(base => Reflect.has(base, p));
},
get(target, p) {
if (p in target) {
// @ts-ignore
return target[p];
}
for (const base of baseInstances) {
if (p in base) {
// @ts-ignore
return base[p];
}
}
// @ts-ignore
return target[p];
},
set(target, p, value) {
if (p in target) {
// @ts-ignore
target[p] = value;
return true;
}
for (const base of baseInstances) {
if (p in base) {
// @ts-ignore
base[p] = value;
return true;
}
}
// @ts-ignore
target[p] = value;
return true;
},
deleteProperty(target, p) {
if (p in target) {
return Reflect.deleteProperty(target, p);
}
for (const base of baseInstances) {
if (p in base) {
return Reflect.deleteProperty(base, p);
}
}
return Reflect.deleteProperty(target, p);
},
ownKeys(target) {
return Reflect.ownKeys(target).concat(baseInstances.flatMap(Reflect.ownKeys)).filter(onlyUnique);
},
// If you want to define a property then you certainly don't want it to be on the base class.
defineProperty(target, p, attributes) {
return Reflect.defineProperty(target, p, attributes);
}
});
}
setPrototypeToProxy(Self, baseClasses);
return Self;
}
exports.bases = bases;
/**
* Defines the properties on the given object, the key represents the name of the property and the value as the, well, value.
* Moreover, if the property name if prefixed with `readonly` then the property will be set to be readonly, ie non-writable, ie any attempts to edit it in strict mode will fail with a `TypeError`.
*
* Use this function to set the properties of the objects inheriting from multiple base classes.
*
* @param v The object on which to define the properties
* @param props A object with the keys as the property names and the values as the values of the properties.
*
* @example
* // In the constructor
* defineProperties(this, {
* <prop>: <value>, // Define a property on `this` with the name <prop> and value <value>
* "readonly <>": <value>, // Define a readonly property on `this` with the name <prop> and value <value>, readonly ie any attempts to edit it in strict mode will fail with a TypeError.
* });
*/
function defineProperties(v, props) {
for (const prop of Reflect.ownKeys(props)) {
if (typeof prop !== "string") {
continue;
}
let propName = prop;
let isWritable = true;
if (prop.startsWith("readonly ")) {
isWritable = false;
propName = prop.slice(9);
}
Reflect.defineProperty(v, propName, {
value: props[prop],
writable: isWritable,
configurable: true,
enumerable: true,
});
}
}
exports.defineProperties = defineProperties;
/**
* Checks if the value `v` is an instance of the class `cls`.
* This function takes into account the multiple base classes.
*
* @param v The object to check.
* @param cls The constructor of the class to check.
* @return Whether or not the object `v` is an instance of the given class `cls`.
*/
function isInstanceOf(v, cls) {
if (v instanceof cls) {
return true;
}
// @ts-ignore
if ('bases' in v && Array.isArray(v.bases)) {
// @ts-ignore
for (const base of v.bases) {
if (isInstanceOf(base, cls)) {
return true;
}
}
}
return false;
}
exports.isInstanceOf = isInstanceOf;
//# sourceMappingURL=index.js.map