Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to parse a string to a function that expects parameters and returns a value?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading