mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-16 12:50:38 -07:00
feat: renderSync, parseAndRenderSync and renderFileSync, see #48
This commit is contained in:
+38
-21
@@ -1,38 +1,55 @@
|
||||
import { assert } from '../util/assert'
|
||||
import { isRange, rangeValue } from './range'
|
||||
import { isRange, rangeValue, rangeValueSync } from './range'
|
||||
import { Value } from './value'
|
||||
import { Context } from '../context/context'
|
||||
import { toValue } from '../util/underscore'
|
||||
import { isOperator, precedence, operatorImpls } from './operator'
|
||||
|
||||
export class Expression {
|
||||
private str: string
|
||||
private operands: any[] = []
|
||||
private postfix: string[]
|
||||
|
||||
public constructor (str: string = '') {
|
||||
this.str = str
|
||||
public constructor (str = '') {
|
||||
this.postfix = [...toPostfix(str)]
|
||||
}
|
||||
public evaluate (ctx: Context): any {
|
||||
public async evaluate (ctx: Context): Promise<any> {
|
||||
assert(ctx, 'unable to evaluate: context not defined')
|
||||
|
||||
const operands = []
|
||||
for (const token of toPostfix(this.str)) {
|
||||
for (const token of this.postfix) {
|
||||
if (isOperator(token)) {
|
||||
const r = operands.pop()
|
||||
const l = operands.pop()
|
||||
const result = operatorImpls[token](l, r)
|
||||
operands.push(result)
|
||||
continue
|
||||
}
|
||||
if (isRange(token)) {
|
||||
operands.push(rangeValue(token, ctx))
|
||||
continue
|
||||
}
|
||||
operands.push(new Value(token).evaluate(ctx))
|
||||
this.evaluateOnce(token)
|
||||
} else if (isRange(token)) {
|
||||
this.operands.push(await rangeValue(token, ctx))
|
||||
} else this.operands.push(await new Value(token).evaluate(ctx))
|
||||
}
|
||||
return operands[0]
|
||||
return this.operands[0]
|
||||
}
|
||||
public value (ctx: Context): any {
|
||||
return toValue(this.evaluate(ctx))
|
||||
public evaluateSync (ctx: Context): any {
|
||||
assert(ctx, 'unable to evaluate: context not defined')
|
||||
|
||||
for (const token of this.postfix) {
|
||||
if (isOperator(token)) {
|
||||
this.evaluateOnce(token)
|
||||
} else if (isRange(token)) {
|
||||
this.operands.push(rangeValueSync(token, ctx))
|
||||
} else {
|
||||
const val = new Value(token).evaluateSync(ctx)
|
||||
this.operands.push(val)
|
||||
}
|
||||
}
|
||||
return this.operands[0]
|
||||
}
|
||||
public async value (ctx: Context): Promise<any> {
|
||||
return toValue(await this.evaluate(ctx))
|
||||
}
|
||||
public valueSync (ctx: Context): any {
|
||||
return toValue(this.evaluateSync(ctx))
|
||||
}
|
||||
private evaluateOnce (token: string) {
|
||||
const r = this.operands.pop()
|
||||
const l = this.operands.pop()
|
||||
const result = operatorImpls[token](l, r)
|
||||
this.operands.push(result)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user