Skip to content

Commit 8620018

Browse files
committed
Add some optimizations for if & filter, for the optimized interpreter.
1 parent c8d7c85 commit 8620018

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

defaultMethods.js

+2
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ const defaultMethods = {
158158
[Sync]: () => true
159159
},
160160
if: {
161+
[OriginalImpl]: true,
161162
method: (input, context, above, engine) => {
162163
if (!Array.isArray(input)) throw INVALID_ARGUMENTS
163164

@@ -868,6 +869,7 @@ function createArrayIterativeMethod (name, useTruthy = false) {
868869
})
869870
)
870871
},
872+
[OriginalImpl]: true,
871873
[Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
872874
method: (input, context, above, engine) => {
873875
if (!Array.isArray(input)) throw INVALID_ARGUMENTS

optimizer.js

+21
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,27 @@ function checkIdioms (logic, engine, above) {
115115
}
116116
}
117117

118+
if ((logic.if || logic['?:']) && engine.methods.if[OriginalImpl] && Array.isArray(logic.if || logic['?:']) && (logic.if || logic['?:']).length === 3) {
119+
const [condition, truthy, falsy] = logic.if || logic['?:']
120+
const C = optimize(condition, engine, above)
121+
const T = optimize(truthy, engine, above)
122+
const F = optimize(falsy, engine, above)
123+
124+
if (typeof C === 'function' && typeof T === 'function' && typeof F === 'function') return (data, abv) => engine.truthy(C(data, abv)) ? T(data, abv) : F(data, abv)
125+
if (typeof C === 'function' && typeof T === 'function') return (data, abv) => engine.truthy(C(data, abv)) ? T(data, abv) : F
126+
if (typeof C === 'function' && typeof F === 'function') return (data, abv) => engine.truthy(C(data, abv)) ? T : F(data, abv)
127+
if (typeof C === 'function') return (data, abv) => engine.truthy(C(data, abv)) ? T : F
128+
129+
// Otherwise, C is not a function, and we can just return the result of the evaluation.
130+
return engine.truthy(C) ? T : F
131+
}
132+
133+
if (logic.filter && engine.methods.filter[OriginalImpl] && Array.isArray(logic.filter) && logic.filter.length === 2) {
134+
const [collection, filter] = logic.filter
135+
const filterF = optimize(filter, engine, above)
136+
if (typeof filterF !== 'function') return engine.truthy(filterF) ? optimize(collection, engine, above) : []
137+
}
138+
118139
// Hyper-Optimizations for Comparison Operators.
119140
for (const comparison in comparisons) {
120141
if (logic[comparison] && Array.isArray(logic[comparison]) && engine.methods[comparison][OriginalImpl]) {

0 commit comments

Comments
 (0)