@@ -88,6 +88,83 @@ describe("transforms", () => {
88
88
} ) ;
89
89
} ) ;
90
90
91
+ describe ( "parameterized transform with non-serializable non-params" , function ( ) {
92
+ it ( "works" , function ( ) {
93
+
94
+ interface Person {
95
+ name : string ;
96
+ age : number ;
97
+ }
98
+
99
+
100
+ const db = new Loki ( "tx.db" ) ;
101
+ const items = db . addCollection < Person > ( "items" ) ;
102
+
103
+ items . insert ( { name : "mjolnir" , age : 5 } ) ;
104
+ items . insert ( { name : "tyrfing" , age : 9 } ) ;
105
+
106
+ let mapper = function ( item : Person ) {
107
+ return item . age ;
108
+ } ;
109
+
110
+ let averageReduceFunction = function ( values : number [ ] ) {
111
+ let sum = 0 ;
112
+
113
+ values . forEach ( function ( i ) {
114
+ sum += i ;
115
+ } ) ;
116
+
117
+ return sum / values . length ;
118
+ } ;
119
+
120
+ // so ideally, transform params are useful for
121
+ // - extracting values that will change across multiple executions, and also
122
+ // - extracting values which are not serializable so that the transform can be
123
+ // named and serialized along with the database.
124
+ //
125
+ // The transform used here is not serializable so this test is just to verify
126
+ // that our parameter substitution method does not have problem with
127
+ // non-serializable transforms.
128
+
129
+ let tx1 = [
130
+ {
131
+ type : "mapReduce" ,
132
+ mapFunction : mapper ,
133
+ reduceFunction : averageReduceFunction
134
+ }
135
+ ] ;
136
+
137
+ let tx2 = [
138
+ {
139
+ type : "find" ,
140
+ value : {
141
+ age : {
142
+ "$gt" : "[%lktxp]minimumAge"
143
+ } ,
144
+ }
145
+ } ,
146
+ {
147
+ type : "mapReduce" ,
148
+ mapFunction : mapper ,
149
+ reduceFunction : averageReduceFunction
150
+ }
151
+ ] as any ;
152
+
153
+ // no data() call needed to mapReduce
154
+ expect ( items . chain ( tx1 ) as any as number ) . toBe ( 7 ) ;
155
+ expect ( items . chain ( tx1 , { foo : 5 } ) as any as number ) . toBe ( 7 ) ;
156
+ // params will cause a recursive shallow clone of objects before substitution
157
+ expect ( items . chain ( tx2 , { minimumAge : 4 } ) as any as number ) . toBe ( 7 ) ;
158
+
159
+ // make sure original transform is unchanged
160
+ expect ( tx2 [ 0 ] . type ) . toEqual ( "find" ) ;
161
+ expect ( tx2 [ 0 ] . value . age . $gt ) . toEqual ( "[%lktxp]minimumAge" ) ;
162
+ expect ( tx2 [ 1 ] . type ) . toEqual ( "mapReduce" ) ;
163
+ expect ( typeof tx2 [ 1 ] . mapFunction ) . toEqual ( "function" ) ;
164
+ expect ( typeof tx2 [ 1 ] . reduceFunction ) . toEqual ( "function" ) ;
165
+ } ) ;
166
+ } ) ;
167
+
91
168
describe ( "parameterized where" , ( ) => {
92
169
it ( "works" , ( ) => {
93
170
0 commit comments