How can I run javascript logic from a string in React Native?

In my application, third party game developers will write simple javascript logic based on my template. They will enter their code into a textbox (online), and I will store their code as Strings.

For example, one game developer would write this:

const examineItem = (user, item, app) => { //we will pass `user` and `item` with our own methods
    //Developer writes his/her own logic
    if(user.intelligence > 50){
        return({ result: "You see a rock!"});
    }else{
        return({ result: "You see nothing"});
    }
};

In my React Native app, how can I "convert" this string code into a runnable function? Do I need some interpreter? Do I use eval (which is deprecated)?

Where do I get started?

2 answers

  • answered 2018-07-11 03:34 Noah Allen

    It's actually not too hard. Use the "new function" operator like so:

    const examineItem = (user, item, app) => {
      // Developer writes his/her own logic
      const devString = 'return user.intelligence > 50'
    
      // You can pass as many arguments as you want, just keep the string last:
      const devFunc = new Function('user', 'item', 'app', devString) 
    
      // Make sure to pass all the arguments to the call:
      if(devFunc(user, item, app)){
        return({ result: "You see a rock!"});
      } else{
        return({ result: "You see nothing"});
      }
    };
    
    // Testing it:
    const user = { intelligence: 60 }
    const res = examineItem(user, null, null)
    console.log(res) // { result: "You see a rock!"}
    

    I just tested this code, and it should work. You could pull the "devString" from wherever you wanted.

    The main danger with this would just be to make sure that all of your devs know which parameters will be passed to the "string" that they write, as well as what the data model is for those parameters.

  • answered 2018-07-11 03:58 Luis Gurmendez

    I made a similar project once, dont forget that custom user code can alter your variables if not properly encapsulated I highly recommend you to read about IIFEs functions.

    Ex. user.intelligence = 1000; // will alter all the user object