Can a getter return a thunk or value depending on the type call call (virt. property or function)?

42 Views Asked by At

I know this a weird question, but I'll ask it anyway.

The pseudo code function below provides a virtual property getter. What it should do is this:


> const calc = Calculator(3)
> calc.multiple    // returns getter result directly
6
> calc.multiple(4) // returns thunk result, thus behaves like a function
12

Here's my pseudo code:

function Calculator(num) {

  return {
    get multiple() {
      if (isFunctionCalled()) {   // isFunctionCalled is an
                                  // imaginary function check
        return (mult = 3) => {
          return mult * num;
        };
      }
      // getter called, default calulation
      return 2 * num;
    },
  };
}
1

There are 1 best solutions below

0
On BEST ANSWER

No, there's no way to know from within multiple whether the value it returns, when used, will be used as a function or used as a non-function.

You could always return a function and provide the immediate value as a property on that function, but you can't return a number in one case but a function in another.

You can also play games with overriding the [Symbol.toPrimitive], valueOf, and/or toString operations on the function you return, but that tends to produce surprising results when used in the wild.

You're probably best off differentiating by name, multiple vs. getMultiple, or multiple vs. multipleThunk, etc.