@maayanpolitzer/rules-engine
Version:
A lightweight, powerful and flexible rule evaluation engine designed for simple or complex logical operations. Perfect for projects requiring customizable validation, dynamic conditions, or decision trees based on json. inspired by MongoDB filters.
2 lines (1 loc) • 2.45 kB
JavaScript
function r(r){return"object"==typeof r&&null!==r&&1===Object.keys(r).length&&Object.keys(r)[0].startsWith("$")}function t(r,t){if("string"==typeof r){const e=r.match(/^{{(.*?)}}$/);if(e){const r=e[1].trim(),n=r.split(".");let o=t;for(const t of n){if(null==o||!(t in o))throw new Error(`Path "${r}" does not exist in context.`);o=o[t]}return o}}return r}var e={$eq:function(e,o={}){if(!Array.isArray(e)||e.length<2)throw new Error("$eq operator expects an array with at least two elements.");const a=e.map((e=>r(e)?n(e,o):t(e,o))),i=a[0];return a.every((r=>r===i))},$gte:function(e,o={}){if(!Array.isArray(e)||2!==e.length)throw new Error("$gte operator expects an array with exactly two elements.");let[a,i]=e;return a=r(a)?n(a,o):t(a,o),i=r(i)?n(i,o):t(i,o),a>=i},$gt:function(r,e={}){if(!Array.isArray(r)||2!==r.length)throw new Error("$gt operator expects an array with exactly two elements.");const[n,o]=r.map((r=>t(r,e)));return n>o},$lt:function(r,e={}){if(!Array.isArray(r)||2!==r.length)throw new Error("$lt operator expects an array with exactly two elements.");const[n,o]=r.map((r=>t(r,e)));return n<o},$lte:function(r,e={}){if(!Array.isArray(r)||2!==r.length)throw new Error("$lte operator expects an array with exactly two elements.");const[n,o]=r.map((r=>t(r,e)));return n<=o},$ne:function(r,e={}){if(!Array.isArray(r)||r.length<2)throw new Error("$ne operator expects an array with at least two elements.");const n=r.map((r=>t(r,e))),o=n[0];return!n.every((r=>r===o))},$and:function(e,o={}){if(!Array.isArray(e))throw new Error("$and operator expects an array.");for(let a of e)if(r(a)){if(!n(a,o))return!1}else if(!t(a,o))return!1;return!0},$in:function(e,o={}){if(!Array.isArray(e)||2!==e.length)throw new Error("$in operator expects an array with exactly two elements.");let[a,i]=e;if(a=r(a)?n(a,o):t(a,o),i=r(i)?n(i,o):t(i,o),!Array.isArray(i))throw new Error("$in operator expects second argument to be an array.");return i.includes(a)},$or:function(e,o={}){if(!Array.isArray(e))throw new Error("$or operator expects an array.");for(let a of e)if(r(a)){if(n(a,o))return!0}else if(t(a,o))return!0;return!1}};function n(t,o){if(!r(t))return t;const[a,i]=Object.entries(t)[0],s=e[a];if(!s)throw new Error(`Unsupported operator: ${a}`);let c=i;return Array.isArray(i)?c=i.map((r=>n(r,o))):r(i)&&(c=n(i,o)),s(c,o)}function o(r,t={}){Array.isArray(r)||(r=[r]);for(const e of r){if(n(e,t))return!0}return!1}export{o as evaluateRules};