0

i have 2 different javascript environments and want to create a library usable on both. to do that i want to use higher order functions to generate my functions, like so

    try {
      Maptool.chat.broadcast("")
      var myFunc1 = genFunction1("env1");
    }
    catch(e){
      if(e instanceof ReferenceError){
        var myFunc1 = genFunction1("env2")
      }
    }

genFunction1 would return a function that i could call built from a function expression. there are only 2 ways i know to generate the function that is returned, it could be written similarly to the next code block with the if outside the inner function which would create a lot of code duplication as i would need to write everything in the function that is unchanged again.

     function genFunction1(env){
       if(env == "env1"){
         return function () {return 3;}
       }
       else{
         return function () {return 2;}
       }  
     }

or with the if inside like the following code block

    genFunction1(env){
      return function (){
        if(env=="env1"){
          return 3;
        }
        return 2;
      }
    }

however if we use a object with a get property which logs when accessed we can see that the third code block calls a if for each call of myFunc1.

    function genFunc1(obj){
      return function (){
        if(obj.env == "env2"){
            console.log("3");
        }
        console.log("2");
      }
    }
    const obj = {
      get env() {
        console.log("accessed property");
        return "env2";
      }
    }
    var myFunc1 = genFunc1(obj);
    myFunc1();
    myFunc1();

as previously said the earlier code block calls the get method once for each call of myFunc1(),but the environment won't change aside from the first time i check, is there any way to make the generated function not include a if and include the if only in the higher order function without duplicating code?

ether
  • 1
  • 2
  • It probably doesn't matter. If the function really is executed often enough for this to matter, the optimising compile will realise that `env=="env1"` is a constant and not evaluate it every time. – Bergi Jun 22 '22 at 14:26
  • There's not a lot code in your function. Can you show us your actual code, please, so that we can help with actually avoiding some code duplication? – Bergi Jun 22 '22 at 14:26

1 Answers1

0

This is expected behavior as you are getting property from an object. Take a snapshot of the value before generating the function, like this.

function genFunc1(obj) {
  var env = obj.env
  return function() {
    if (env == "env2") {
      console.log("3");
    }
    console.log("2");
  }
}
IT goldman
  • 14,885
  • 2
  • 14
  • 28