/
operator.ts
50 lines (48 loc) · 1.81 KB
/
operator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { isComparable } from '../drop/comparable'
import { Context } from '../context'
import { isFunction, toValue } from '../util'
import { isFalsy, isTruthy } from '../render/boolean'
export type UnaryOperatorHandler = (operand: any, ctx: Context) => boolean;
export type BinaryOperatorHandler = (lhs: any, rhs: any, ctx: Context) => boolean;
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)
},
'>': (l: any, r: any) => {
if (isComparable(l)) return l.gt(r)
if (isComparable(r)) return r.lt(l)
return toValue(l) > toValue(r)
},
'<': (l: any, r: any) => {
if (isComparable(l)) return l.lt(r)
if (isComparable(r)) return r.gt(l)
return toValue(l) < toValue(r)
},
'>=': (l: any, r: any) => {
if (isComparable(l)) return l.geq(r)
if (isComparable(r)) return r.leq(l)
return toValue(l) >= toValue(r)
},
'<=': (l: any, r: any) => {
if (isComparable(l)) return l.leq(r)
if (isComparable(r)) return r.geq(l)
return toValue(l) <= toValue(r)
},
'contains': (l: any, r: any) => {
l = toValue(l)
r = toValue(r)
return l && isFunction(l.indexOf) ? l.indexOf(r) > -1 : false
},
'not': (v: any, ctx: Context) => isFalsy(toValue(v), ctx),
'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)
}