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?

2
  • 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? Commented Nov 10, 2022 at 10:34
  • This might help you. Commented Nov 10, 2022 at 10:35

2 Answers 2

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
  });
}

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

yes, but I thought the "never use eval" section shows that Function is a valid alternative
problem might be the arrow function in functionAsString, have you try the normal function declaration ?
you mean like so? jsfiddle.net/f0e2wnLj this syntax didn't work for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.