-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetadata.ts
51 lines (50 loc) · 1.33 KB
/
metadata.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
/**
* A way to attach additional hidden properties to an object.
*
* Example:
* ```ts
* const hiddenProperty = metadata<string>("optional label")
* const obj = {}
* hiddenProperty.set(obj, "value")
* // obj looks the same as before, just a plain object
* console.log(obj) // {}
* console.log(hiddenProperty.get(obj)) // "value"
* ```
*/
export function metadata<Value>() {
return class GetterSetter extends Stamper {
#value: Value | undefined
static set(object: unknown, value: Value) {
if (
typeof object === "object" &&
object !== null &&
#value in object
) {
object.#value = value
} else {
this.#attach(object).#value = value
}
}
static get(object: unknown): Value | undefined {
if (
typeof object === "object" &&
object !== null &&
#value in object
) {
return object.#value
}
}
static #attach(object: unknown) {
return new this(object)
}
}
}
/**
* Allows subclasses to stamp private fields onto an
* object without altering the object's prototype.
*/
class Stamper {
constructor(object: unknown) {
return object as any
}
}