-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathoop.js
58 lines (53 loc) · 1.58 KB
/
oop.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
'use strict';
// Override method: save old to `fn.inherited`
// Previous function will be accessible by obj.fnName.inherited
// obj - <Object>, containing method to override
// fn - <Function>, name will be used to find method
const override = (obj, fn) => {
fn.inherited = obj[fn.name];
obj[fn.name] = fn;
};
// Mixin for ES6 classes without overriding existing methods
// target - <Object>, mixin to target
// source - <Object>, source methods
const mixin = (target, source) => {
const methods = Object.getOwnPropertyNames(source);
const mix = {};
for (const method of methods) {
if (!target[method]) {
mix[method] = source[method];
}
}
Object.assign(target, mix);
};
const ASCII_A = 65;
// Convert instance with public fields to instance with private fields
// instance - <Object>, source instance
// Returns: <Object> - destination instance
//
// Example: common.privatize({ private: 5, f() { return this.private; } });
const privatize = instance => {
const iface = {};
const fields = Object.keys(instance);
for (const fieldName of fields) {
const field = instance[fieldName];
if (typeof field === 'function') {
const boundMethod = field.bind(instance);
iface[fieldName] = boundMethod;
} else if (fieldName === fieldName.toUpperCase()) {
const first = fieldName.charCodeAt(0);
if (first >= ASCII_A) {
Object.defineProperty(iface, fieldName, {
enumerable: true,
get: () => field,
});
}
}
}
return Object.freeze(iface);
};
module.exports = {
override,
mixin,
privatize,
};