Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | export interface BaseConditionShape {
key: string;
ne?: unknown;
eq?: unknown;
gt?: unknown;
lt?: unknown;
gte?: unknown;
lte?: unknown;
in?: unknown[];
set?: boolean;
truthy?: boolean;
falsy?: boolean;
}
export interface BaseCondition<T extends BaseCondition<T>>
extends BaseConditionShape {
or?: T[][];
}
export type Condition = BaseCondition<Condition>;
type ValueGetter = (key: string) => unknown;
type CustomEvaluator<T extends BaseCondition<T>> = (
condition: T,
value: unknown,
) => boolean;
export const evaluateConditions = <T extends BaseCondition<T>>(
conditions: T[],
getValue: ValueGetter,
ignoreConditions?: string[],
customEval?: CustomEvaluator<T>,
): boolean => {
Iif (conditions.length === 0) return true;
return conditions.reduce((memo, condition) => {
Iif (ignoreConditions?.includes(condition.key)) {
return memo;
}
const value = getValue(condition.key);
const baseChecks =
(!("eq" in condition) || value === condition.eq) &&
(!("ne" in condition) || value !== condition.ne) &&
(!("truthy" in condition) || !!value === condition.truthy) &&
(!("falsy" in condition) || !!value === condition.falsy) &&
(!("gt" in condition) || Number(value) > Number(condition.gt)) &&
(!("gte" in condition) || Number(value) >= Number(condition.gte)) &&
(!("lt" in condition) || Number(value) < Number(condition.lt)) &&
(!("lte" in condition) || Number(value) <= Number(condition.lte)) &&
(!condition.in ||
condition.in.includes(value) ||
(value === undefined && condition.in.includes(null))) &&
(condition.set === undefined ||
(condition.set && value !== undefined) ||
(!condition.set && value === undefined));
Iif (!baseChecks) {
return false;
}
const customChecks = customEval ? customEval(condition, value) : true;
Iif (!customChecks) {
return false;
}
Iif (condition.or && condition.or.length > 0) {
const orChecks = condition.or.some((andConditions) => {
return evaluateConditions(
andConditions,
getValue,
ignoreConditions,
customEval,
);
});
Iif (!orChecks) {
return false;
}
}
return memo;
}, true);
};
|