-
Notifications
You must be signed in to change notification settings - Fork 0
/
mixin.ts
204 lines (180 loc) · 6.23 KB
/
mixin.ts
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
import {
MacroOptions,
MacroProperties,
MacroCallback,
Macroed,
Macroable,
AssignedPropertyKey,
AssignCallback,
} from './types';
import isMacroable from './is/isMacroable';
import isMacroed from './is/isMacroed';
import isMacroedWith from './is/isMacroedWith';
import assign from './utils/assign';
import {
DEFAULT_FUNCTION_PROTOTYPE_PROPERTIES,
DEFAULT_FUNCTION_STATIC_PROPERTIES,
} from './constants/functionDefaultProperties';
const defaultOptions: MacroOptions = {
force: false,
onFunctionPrototype: true,
};
/**
* Register a collection of macros on a given target.
*
* This function, as opposed to the `macro()` function, allows us
* to register multiple properties/methods at once on a given target.
*
* It has the following signature:
* - **target** (`unknown`): The object/function onto which the new properties/methods should be added.
* - **properties** (`object`|`function`):
* - If an object, the keys will be used for the property name and it's value for the property's implementation.
* - If a function, all it's static and prototype enumerable own properties will be copied over onto the target.
* - **callback** (`function` | `null`): A function, when present, gives us full control over how we'd like the copying to proceed.
* - **options** (`MacroOptions`):
* - **force** (`boolean` | defaults to `false`): Force replace existing properties and/or properties previously added via macro.
* - **onFunctionPrototype** (`boolean` | defaults to `true`): When the target is a function, should the new property be
* added to the target's prototype or to the target directly,
* essentially making it a static property.
*
* @example
* ```js
* import { mixin } from '@vicgutt/macrojs';
*
* const target = [];
*
* mixin(target, {
* hello: () => 'hello!',
* isEmpty() {
* return this.length === 0;
* },
* });
*
* target.hello(); // 'hello!'
* target.isEmpty(); // true
*
* mixin(
* { name: 'Bob', age: NaN },
* {
* isHuman: '🤔',
* isTroubleMaker: '👀',
* },
* (propertyKey, target, properties, options) => {
* console.log(propertyKey, target, properties, options);
* }
* );
*
* // isHuman { name: 'Bob', age: NaN } { isHuman: '🤔', isTroubleMaker: '👀' } { force: false, onFunctionPrototype: true }
* // isTroubleMaker { name: 'Bob', age: NaN } { isHuman: '🤔', isTroubleMaker: '👀' } { force: false, onFunctionPrototype: true }
* ```
*/
export default function mixin<T, P extends MacroProperties>(
target: T,
properties: P,
callback: MacroCallback<T, P> = null,
options: MacroOptions = {}
): void {
options = { ...defaultOptions, ...(options || {}) };
if (!properties || !['object', 'function'].includes(typeof properties) || Array.isArray(properties)) {
return;
}
if (typeof properties === 'function') {
handleFunctionProperties(target, properties, callback, options);
} else {
handleObjectProperties(target, properties, callback, options);
}
}
function handleFunctionProperties<T, P extends Function>( // eslint-disable-line @typescript-eslint/ban-types
target: T | Macroable,
properties: P,
callback: MacroCallback<T, P>,
options: MacroOptions
): void {
const props = {
static: properties,
proto: properties.prototype ?? {},
};
if (callback) {
[
...Object.getOwnPropertyNames(props.static),
...Object.getOwnPropertySymbols(props.static),
...Object.getOwnPropertyNames(props.proto),
...Object.getOwnPropertySymbols(props.proto),
].forEach((name) => {
callback(name, target, properties, options);
});
return;
}
if (!isMacroable(target)) {
return;
}
const assignedStaticPropKeys: AssignedPropertyKey[] = [];
const assignedProtoPropKeys: AssignedPropertyKey[] = [];
assign(
target,
props.static,
assignCallback(target, options, assignedStaticPropKeys, DEFAULT_FUNCTION_STATIC_PROPERTIES)
);
markAsMacroed(target, assignedStaticPropKeys);
if (typeof target === 'function' && isMacroable(target.prototype)) {
target = target.prototype;
}
assign(
target,
props.proto,
assignCallback(target, options, assignedProtoPropKeys, DEFAULT_FUNCTION_PROTOTYPE_PROPERTIES)
);
markAsMacroed(target, assignedProtoPropKeys);
}
function handleObjectProperties<T, P extends MacroProperties>(
target: T | Macroable,
properties: P,
callback: MacroCallback<T, P>,
options: MacroOptions
): void {
if (callback) {
[...Object.getOwnPropertyNames(properties), ...Object.getOwnPropertySymbols(properties)].forEach((name) => {
callback(name, target, properties, options);
});
return;
}
if (typeof target === 'function' && options.onFunctionPrototype && isMacroable(target.prototype)) {
target = target.prototype;
}
if (!isMacroable(target)) {
return;
}
const assignedPropKeys: AssignedPropertyKey[] = [];
assign(target, properties, assignCallback(target, options, assignedPropKeys));
markAsMacroed(target, assignedPropKeys);
}
function assignCallback(
target: Macroable,
options: MacroOptions,
assignedPropKeys: AssignedPropertyKey[],
excludeList: string[] = []
): AssignCallback {
return (name) => {
if (excludeList.includes(name as string)) {
return false;
}
if (!options.force && (name in target || isMacroedWith(target, name))) {
return false;
}
assignedPropKeys.push(name);
return;
};
}
function markAsMacroed(target: Macroable, assignedPropKeys: AssignedPropertyKey[]) {
if (assignedPropKeys.length && !isMacroed(target)) {
Object.defineProperty(target, '__macros__', {
value: new Set(),
writable: false,
enumerable: false,
configurable: false,
});
}
assignedPropKeys.forEach((key) => {
(target as unknown as Macroed).__macros__.add(key as string);
});
}