skip to Main Content

I have a function-returning function. The inner function makes use of the parent function’s argument in its body. Then I make a list of functions produced by calling the parent function with different arguments. Here is an example:

function f(a) { return function(b) { return a * a + b; }; }
var fList = [f(-2), f(-1), f(0), f(1), f(2)];

Those are from a library and I cannot modify them.

I was wondering if there is any possibility to apply a filter on the fList based on the value of the argument of f. For example can I get the items in fList where the f function is called with a non-negative value? I tried inspecting fList[0] in debug console but could not make any progress unfortunately.

I feel like this is not possible. However, since when I call fList[0](2) it uses the a variable’s value of -2, I am hoping so.

Please do not suggest using an inverse function, that’s why I made it return the square of the searched argument plus the inner one. Above is an over-simplified example and the body in the real case is much different with some side effects.

2

Answers


  1. if your fList is in numerical order (as you show above), then you know that every element in fList before the result of 0 (ie f(0) = 0 * 0 + 0 = 0) is from a negative number

    Login or Signup to reply.
  2. If you can override f:

    function f(a) { return function(b) { return a * a + b; }; }
    
    const param = Symbol();
    // override f() and assign the param to it
    f = a => {
      const out = b => a * a + b;
      out[param] = a;
      return out;
    };
    
    var fList = [f(-2), f(-1), f(0), f(1), f(2)];
    
    const positive = fList.filter(f => f[param] >= 0);
    
    console.log(positive.map(f=>f(3)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search