JSFiddle - React, Tailwind, and code Playground

by Abhishek Kumar

JavaScript

function sqlWhereToFunction(whereClause) {
  const operators = {
    '=': '===',
    '<>': '!==',
    '>': '>',
    '<': '<',
    '>=': '>=',
    '<=': '<=',
    'AND': '&&',
    'OR': '||'
  };
  let jsCondition = whereClause;
  for (const [sqlOp, jsOp] of Object.entries(operators)) {
    jsCondition = jsCondition.split(sqlOp).join(jsOp);
  }
  return new Function('row', `return ${jsCondition};`);
}

const customers = [
  { id: 1, name: 'Alice', age: 30 },
  { id: 2, name: 'Bob', age: 40 },
  { id: 3, name: 'Charlie', age: 50 }
];

const whereFunction = sqlWhereToFunction('age >= 40');
const filteredCustomers = customers.filter(whereFunction);
console.log(filteredCustomers);
// Output: [ { id: 2, name: 'Bob', age: 40 }, { id: 3, name: 'Charlie', age: 50 } ]