samedi 9 juillet 2022

Can JavaScript override variable values using another closure at runtime?

Say I want to use one function to 'decorate' another with input/output. But I want this wrapping to be optional, and if used, the function wrap 'shadows' the variable within the closure.

I have an object called customSettings that contains lambda functions that can be called, and also uses the variable 'green' within.

In 'wrap' I try to override the green variable value. Can I avoid hardcoding the variable name 'green' in 'wrap'?

Eventually I'm thinking 'wrap' will be the generalized function, and the user uses it to define wrappingFunc, where for example the anonymous function '(g)=>' returns an object. Then for each value that exists inside the object structure (eg. obj['greens']), it overrides variable's value within the context of the closure of the function specified.

Running the code with 'green' hardcoded also doesn't work -- the original closure's variable value is still being used.

Is this sort of variable name overriding possible in JavaScript? If not any pointers to this scenario?

    let greens = 100;
    // Defined object structure with specified keyword 'color' to be called by another function
    let customSettings: DrawSettingLambdas = new DrawSettingLambdas(GlobalDrawSetting, {
      color: () => {
        // Issue is here: I want to wrap this lambda object eventually with 'wrap', but I don't want to let the variable name 'greens' be hardcoded. Now I can hardcode a 'common' variable contextObj but then I can't use it for normal use cases now.
        // If i use 'greens', I'll have to write greens in the function below.
        //greens
        return ColorConversions.rgbToHex(0, contextObj['green'], 0);
      }
    });


    // Quick wrap
    function wrap(obj, contextLambda) {
      return (inputLambda) => {
        // Variable name contextObj is hardcoded.
        let contextObj = {"green": contextLambda(inputLambda)};
        return obj;
      }
    }
    
    // eg. greens 1, 2, 3 returns the correct context numbers....
    let wrappingFunc = wrap(customSettings, (g)=>{return g * 100;});
    
    // Use wrap
    draw.AddGraph(subtractResults3, canvasRectangle3, [], wrappingFunc(1));
    draw.AddGraph(subtractResults2, canvasRectangle3, [], wrappingFunc(2));
    draw.AddGraph(subtractResults1, canvasRectangle3, [], wrappingFunc(3));




Aucun commentaire:

Enregistrer un commentaire