111 lines
2.4 KiB
JavaScript
111 lines
2.4 KiB
JavaScript
import {fromJSON as behaviorItemFromJSON} from './registry';
|
|
|
|
export class Condition {
|
|
|
|
static type() {
|
|
return 'condition';
|
|
}
|
|
|
|
constructor() {
|
|
this.operator = '';
|
|
this.operands = [];
|
|
}
|
|
|
|
check(context) {
|
|
return this.get(context);
|
|
}
|
|
|
|
clone(other) {
|
|
this.operator = other.operator;
|
|
this.operands = other.operands.map((operand) => operand.clone());
|
|
}
|
|
|
|
fromJSON(json) {
|
|
this.operator = json.operator;
|
|
this.operands = json.operands.map((operand) => {
|
|
return behaviorItemFromJSON(operand);
|
|
});
|
|
return this;
|
|
}
|
|
|
|
get(context) {
|
|
switch (this.operator) {
|
|
case 'is':
|
|
return this.operands[0].get(context) === this.operands[1].get(context);
|
|
case 'isnt':
|
|
return this.operands[0].get(context) !== this.operands[1].get(context);
|
|
case '>':
|
|
return this.operands[0].get(context) > this.operands[1].get(context);
|
|
case '>=':
|
|
return this.operands[0].get(context) >= this.operands[1].get(context);
|
|
case '<':
|
|
return this.operands[0].get(context) < this.operands[1].get(context);
|
|
case '<=':
|
|
return this.operands[0].get(context) <= this.operands[1].get(context);
|
|
|
|
case 'or':
|
|
if (0 === this.operands.length) {
|
|
return true;
|
|
}
|
|
for (const operand of this.operands) {
|
|
if (!!operand.get(context)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
|
|
case 'and':
|
|
if (0 === this.operands.length) {
|
|
return true;
|
|
}
|
|
for (const operand of this.operands) {
|
|
if (!operand.get(context)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
|
|
case 'contains':
|
|
if (this.operands.length < 2) {
|
|
return false;
|
|
}
|
|
const haystack = this.operands[0].get(context);
|
|
const needle = this.operands[1].get(context);
|
|
return -1 !== haystack.indexOf(needle);
|
|
|
|
}
|
|
}
|
|
|
|
operandCount() {
|
|
return this.operands.length;
|
|
}
|
|
|
|
operand(index) {
|
|
return this.operands[index];
|
|
}
|
|
|
|
operands() {
|
|
return this.operands;
|
|
}
|
|
|
|
operator() {
|
|
return this.operator;
|
|
}
|
|
|
|
setOperand(index, operand) {
|
|
this.operands[index] = operand;
|
|
}
|
|
|
|
setOperator(operator) {
|
|
this.operator = operator;
|
|
}
|
|
|
|
toJSON() {
|
|
return {
|
|
type: 'condition',
|
|
operator: this.operator,
|
|
operands: this.operands.map((operand) => operand.toJSON()),
|
|
};
|
|
}
|
|
}
|