0

Here's what I'm talking about.

Algebra.twoplustwo() //4
Algebra.fourtimesnine() //36

When a function in Algebra is called, the object has a single handler which parses the name of the function called to figure out what to do.

Is this possible? Do objects have a default function that runs if no function is found?

  • *"Is this possible?"* **Yes** *" Do objects have a default function that runs if no function is found?*" **No, you can use a conditional and simply return the function if the condition is not met or call a function you made yourself** – zer00ne Mar 26 '17 at 18:50

1 Answers1

1

Yes, it is possible with an ES6 Proxy on an empty object:

var Algebra = new Proxy({}, {
    // Intercept member access:
    get: function(target, name) {
        // Helper function to translate word to number
        // -- extend it to cover for more words:
        function toNumber(name) {
            var pos = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"].indexOf(name);
            return pos === -1 ? NaN : pos;
        }
        // See if we can understand the name:
        var parts = name.split('plus');
        if (parts.length > 1) {
            parts = parts.map(toNumber);
            // Return result as a function:
            return _ => parts[0] + parts[1];
        }
        var parts = name.split('times');
        if (parts.length > 1) {
            parts = parts.map(toNumber);
            // Return result as a function:
            return _ => parts[0] * parts[1];
        }
    }
});

// Sample calls:
console.log(Algebra.twoplustwo());
console.log(Algebra.fourtimesnine());

As you can see, it is not really needed that these names are called as methods, you might as well interpret them as properties:

Instead of returning a function:

            return _ => parts[0] * parts[1];

... you could just return the result:

            return parts[0] * parts[1];

And then you access it as a property:

Algebra.threetimesfour
trincot
  • 317,000
  • 35
  • 244
  • 286