fix: [expression] apply value equal for arrays, #589

This commit is contained in:
Harttle
2023-03-02 23:44:56 +08:00
parent 42d25902e8
commit 9c0dc5fa39
3 changed files with 38 additions and 10 deletions
+19 -10
View File
@@ -2,6 +2,7 @@ import { isComparable } from '../drop/comparable'
import { Context } from '../context'
import { isFunction, toValue } from '../util'
import { isFalsy, isTruthy } from '../render/boolean'
import { isArray } from '../util/underscore';
export type UnaryOperatorHandler = (operand: any, ctx: Context) => boolean;
export type BinaryOperatorHandler = (lhs: any, rhs: any, ctx: Context) => boolean;
@@ -9,16 +10,8 @@ export type OperatorHandler = UnaryOperatorHandler | BinaryOperatorHandler;
export type Operators = Record<string, OperatorHandler>
export const defaultOperators: Operators = {
'==': (l: any, r: any) => {
if (isComparable(l)) return l.equals(r)
if (isComparable(r)) return r.equals(l)
return toValue(l) === toValue(r)
},
'!=': (l: any, r: any) => {
if (isComparable(l)) return !l.equals(r)
if (isComparable(r)) return !r.equals(l)
return toValue(l) !== toValue(r)
},
'==': equal,
'!=': (l: any, r: any) => !equal(l, r),
'>': (l: any, r: any) => {
if (isComparable(l)) return l.gt(r)
if (isComparable(r)) return r.lt(l)
@@ -48,3 +41,19 @@ export const defaultOperators: Operators = {
'and': (l: any, r: any, ctx: Context) => isTruthy(toValue(l), ctx) && isTruthy(toValue(r), ctx),
'or': (l: any, r: any, ctx: Context) => isTruthy(toValue(l), ctx) || isTruthy(toValue(r), ctx)
}
function equal(lhs: any, rhs: any): boolean {
if (isComparable(lhs)) return lhs.equals(rhs)
if (isComparable(rhs)) return rhs.equals(lhs)
lhs = toValue(lhs)
rhs = toValue(rhs)
if (isArray(lhs)) {
return isArray(rhs) && arrayEqual(lhs, rhs)
}
return lhs === rhs
}
function arrayEqual(lhs: any[], rhs: any[]): boolean {
if (lhs.length !== rhs.length) return false
return !lhs.some((value, i) => !equal(value, rhs[i]))
}