2

After reading up online I wrote this simple code that does addition and multiplication via chaining. But reading the code, it looks like to me, that the method "Result" makes the code less readable and kind of seems redundant. Can someone help me get rid of the Result function?

var Calculator = function () {
    var result = 0;
    this.Add = function (x) {

        result = result + x;

        return this;
    };

     this.Multiply = function (x) {

        result = result * x;

        return this;
    };

    this.Result = function () {
        return result;
    }

};


var total = new Calculator().Add(2).Add(3).Multiply(5);

alert(total.Result());

What I am trying to achieve is

var total = new Calculator().Add(2).Add(3).Multiply(5);

alert(total);
developer747
  • 15,419
  • 26
  • 93
  • 147
  • 1
    Well, `total` isn't really a total, is it? It's a `Calculator` object. – Robert Harvey Jan 02 '15 at 01:04
  • Your question is very similar to this one: [How to achieve arbitrary chain on function call in javascript?](http://stackoverflow.com/questions/26656718/how-to-achieve-arbitrary-chain-on-function-call-in-javascript) Look for the answers by mintsauce and friedi. – Qantas 94 Heavy Jan 02 '15 at 01:05
  • Why don't you just chain `.Result()` at the end? (Unrelated note: there's an informal JS standard that non-constructor method names start with a lower-case letter.) – nnnnnn Jan 02 '15 at 01:12

2 Answers2

6

You could do some interesting stuff with prototyping:

var Calculator = function(){ /*...*/ }

// Works with alert
Calculator.prototype.toString = function(){
   return this.Result();
}

// Works with operators
Calculator.prototype.valueOf = function(){
   return this.Result();
}

var total = new Calculator().Add(2).Add(3).Multiply(5);
alert(total); // 25
total + 1; // 26

Note that the function alert(...) converts the arguments to strings before being displayed using .toString(). This also applies to any other operation that has strings, such as concatenation (ex. total + ""). Operations with numbers use .valueOf() instead.

JCOC611
  • 19,111
  • 14
  • 69
  • 90
1

I think returning .Result() is perfectly fine, since you cannot have the chainable methods return one type and then in the end auto-magically turn into something else.

Even the other suggested answers are using methods to turn your Calculator into a result, they are just implicitly invoked by the runtime (e.g. toString in the alert function).

If you want real chaining of numbers you should extend the Number prototype and not use a calculator (but i know, Monkey-patching is evil).

Faris Zacina
  • 14,056
  • 7
  • 62
  • 75