Home > Software design >  How to parse a string to a function that expects parameters and returns a value?
How to parse a string to a function that expects parameters and returns a value?

Time:11-10

It is possible to configure functions as strings to parse them to functions during runtime.

The following example functionAsString expects input and deals with it, I only know that it MUST return a boolean ( I'm expecting that )

const x = {
  fields: {
    age: 0
  }
};
const y = {
  fields: {
    age: 1
  }
};

const functionAsString = "(left, right) => left.fields.age < right.fields.age";
const compareFunction = new Function(functionAsString);

const isXLessThanY = compareFunction(x, y);

if (isXLessThanY === undefined) {
  console.error("it should not be undefined...");
} else {
  console.log({
    isXLessThanY
  });
}

isXLessThanY is undefined. Do you know how to setup a valid function based on a string?

CodePudding user response:

The Function constructor actually takes more structured data than eval, it takes the parameter names, then the body. Also it does generate a regular function (not an arrow function) so you have to explicitly return.

const x = {
  fields: {
    age: 0
  }
};
const y = {
  fields: {
    age: 1
  }
};

const functionAsString = "return left.fields.age < right.fields.age";
const compareFunction = new Function('left', 'right', functionAsString);

const isXLessThanY = compareFunction(x, y);

if (isXLessThanY === undefined) {
  console.error("it should not be undefined...");
} else {
  console.log({
    isXLessThanY
  });
}

CodePudding user response:

you can use eval() function to run js code as a string, but it has some security issues. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

  • Related