-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdefine.ts
51 lines (47 loc) · 1.51 KB
/
define.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
import typeOf from "./typeOf.ts";
/**
* Sets a property on the target object.
* @param value Normally this is the value bound to the property, however, it
* could be used to set the getter and the setter using the signature
* `{ get: Function, set?: Function }`.
* @param enumerable By default, the property is non-enumerable and can't be
* seen by the console, use this option to make it enumerable and visible to
* the console.
* @param writable By default, the property is readonly once set, use this
* option to allow it being writable.
* **This property doesn't work with setter.**
*/
export default function define(
obj: any,
prop: string | symbol,
value: any,
enumerable = false,
writable = false,
): void {
if ((typeOf(value) as any) === Object) {
if (isGetter(value) || isGetterAndSetter(value)) {
Object.defineProperty(obj, prop, {
configurable: true,
enumerable,
...value
});
return;
}
}
Object.defineProperty(obj, <string | symbol>prop, {
configurable: true,
enumerable,
writable,
value
});
}
function isGetter(obj: any) {
return String(Object.keys(obj)) === "get"
&& typeof obj["get"] === "function";
}
function isGetterAndSetter(obj: any) {
let sign = String(Object.keys(obj));
return (sign === "get,set" || sign === "set,get")
&& typeof obj["get"] === "function"
&& typeof obj["set"] === "function";
}