@@ -11,15 +11,119 @@ import { Collection as CollectJS } from 'collect.js'
1111
1212export class Collection < T = any > extends CollectJS < T > {
1313 /**
14- * An alias for macro instance method:
14+ * Add standard property to your class prototype.
1515 *
1616 * @example
17- * Collection.macro('upperAndTrim', (value) => {
18- * return value.trim().toUpperCase()
19- * })
17+ * ```ts
18+ * YourClass.macro('foo', 'bar')
19+ * ```
20+ */
21+ public static macro < K extends keyof Collection > (
22+ name : K ,
23+ value : Collection [ K ]
24+ ) {
25+ this . prototype [ name ] = value
26+ }
27+
28+ /**
29+ * Add getters to the class prototype using the Object.defineProperty()
30+ * method.
31+ *
32+ * @example
33+ * ```ts
34+ * YourClass.getter('foo', function foo () {
35+ * return 'bar'
36+ * })
37+ *
38+ * const singleton = true
39+ *
40+ * // Add singleton getter:
41+ * YourClass.getter('foo', function foo() {
42+ * return 'bar'
43+ * }, singleton)
44+ * ```
2045 */
21- public static macro ( name : string , fn : any ) : void {
22- return new Collection ( ) . macro ( name , fn )
46+ public static getter < K extends keyof Collection > (
47+ name : K ,
48+ accumulator : ( ) => Collection [ K ] ,
49+ singleton : boolean = false
50+ ) {
51+ Object . defineProperty ( this . prototype , name , {
52+ get ( ) {
53+ const value = accumulator . call ( this )
54+
55+ if ( singleton ) {
56+ Object . defineProperty ( this , name , {
57+ configurable : false ,
58+ enumerable : false ,
59+ value,
60+ writable : false
61+ } )
62+ }
63+
64+ return value
65+ } ,
66+ configurable : true ,
67+ enumerable : false
68+ } )
69+ }
70+
71+ /**
72+ * Add a standard static property to the class itself.
73+ *
74+ * @example
75+ * ```ts
76+ * YourClass.staticMacro('foo', 'bar')
77+ * ```
78+ */
79+ public static staticMacro < K extends keyof Collection > (
80+ name : K ,
81+ value : Collection [ K ]
82+ ) {
83+ Object . defineProperty ( this , name , {
84+ value,
85+ writable : true ,
86+ enumerable : true ,
87+ configurable : true
88+ } )
89+ }
90+
91+ /**
92+ * Add static getters to the class itself using Object.defineProperty().
93+ *
94+ * @example
95+ * ```ts
96+ * YourClass.staticGetter('foo', () => 'bar')
97+ *
98+ * const singleton = true
99+ *
100+ * // Add singleton static getter:
101+ * YourClass.staticGetter('foo', () => 'bar', singleton)
102+ * ```
103+ */
104+ public static staticGetter < K extends keyof Collection > (
105+ name : K ,
106+ accumulator : ( ) => Collection [ K ] ,
107+ singleton : boolean = false
108+ ) {
109+ Object . defineProperty ( this , name , {
110+ get : function ( ) {
111+ const value = accumulator . call ( this )
112+
113+ if ( singleton ) {
114+ Object . defineProperty ( this , name , {
115+ configurable : false ,
116+ enumerable : true ,
117+ value,
118+ writable : false
119+ } )
120+ }
121+
122+ return value
123+ } ,
124+ configurable : true ,
125+ enumerable : true
126+ } )
23127 }
24128
25129 /**
0 commit comments