JSFiddle - React, Tailwind, and code Playground

by Znarkus

HTML

Output:
<pre id="output"></pre>

JavaScript

const rules = [
	[
  	{ variableId: 1 },
    'includes',
    ['creative', 'kreativ']
  ],
  'and',
  [
  	{ variableId: [2,3,4], match: 'anyOf' },
    'startsWith',
    'program'
  ]
]

const renderedVariables = {
	1: 'kreativ',
}

const evaluateLeft = (left) => {
	let leftValue
  let multiValueComp
  
  if (left.variableId) {
  	if (Array.isArray(left.variableId)) {
    	leftValue = left.variableId.map(id => renderedVariables[id])
      multiValueComp = left.match
    } else {
	  	leftValue = renderedVariables[left.variableId]
    }
  }
  
  return [leftValue, multiValueComp]
}

const compare = (leftValue, comp, right) => {
	switch (comp) {
  	case 'includes':
    	return leftValue.includes(right)
  	case 'startsWith':
    	return leftValue.startsWith(right)
	}
}

const evaluateRule = (rule) => {
  const [left, comp, right] = rule
  const [leftValue, multiValueComp] = evaluateLeft(left)
  
  if (Array.isArray(leftValue)) {
	  if (multiValueComp === 'anyOf') {
  		return leftValue.some(v => compare(v, comp, right))
    }
  } else if (Array.isArray(right)) {
	  return right.some(v => compare(leftValue, comp, v))
  } else {
  	return compare(leftValue, comp, right)
  }
}

document.getElementById('output').innerText = JSON.stringify(rules[0], null, 2) + ' = ' + JSON.stringify(evaluateRule(rules[0]))