Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    },
  };
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading