0

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?

baitendbidz
  • 187
  • 3
  • 19
  • 1
    It would need to be `new Function("left", "right", "return left.fields.age < right.fields.age")`, but that's almost just as bad as using `eval()` and can be a security risk if these strings are user provided. What is the reason why you need to have the function as a string in the first place? – Nick Parsons Nov 10 '22 at 10:34
  • [This](https://stackoverflow.com/questions/7650071/is-there-a-way-to-create-a-function-from-a-string-with-javascript) might help you. – c0m1t Nov 10 '22 at 10:35

2 Answers2

1

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

1

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
  });
}
Guerric P
  • 30,447
  • 6
  • 48
  • 86