ben121
ben121

Reputation: 897

Addition of two or more functions in javascript

I have a function which gives three objects

function myfunc(one, two, three){
    this.one = one;
    this.two = two;
    this.three = three;
}

var a = new myfunc(6,5,7);
var b = new myfunc(10,4,2);
var c = new mufunc(20,1,8);

This gives the three separate objects which are useful. However, i want to create a forth object which is the sum of a,b and c. In effect this would be the same as:

var all = new myfunc(36, 10, 17); 

I can do this manually:

aa = a.one + b.one + c.one
bb = a.two + b.two + c.two
cc = a.three + b.three + c.three

var all = new myfunc(aa, bb, cc)

but is there a better way which is less manual.

Upvotes: 0

Views: 74

Answers (3)

Arun Gupta
Arun Gupta

Reputation: 1

function myfunc(one, two, three){
    this.one = one;
    this.two = two;
    this.three = three;
}

myfunc.prototype.add = function(){
    return this.one + this.two + this.three
}

var all = new myfunc(36, 10, 17);
all.add()

Upvotes: -2

BenM
BenM

Reputation: 53198

The only way to achieve this is to create a function to handle this for you, if you're going to be running it regularly. Just pass in the objects and the function will handle it:

function sum_objects( obj1, obj2, obj3 )
{
  return new myfunc(
    (obj1.one + obj2.one + obj3.one),
    (obj1.two + obj2.two + obj3.two),
    (obj1.three + obj2.three + obj3.three)
  );
}

Upvotes: 1

Bergi
Bergi

Reputation: 664464

You could put them into an array and sum their properties in a loop of course:

var list = [a, b, c];
function sum(arr, prop) {
    return arr.reduce((acc, x) => acc+x[prop], 0);
}
var all = new myfunc(sum(list, "one"), sum(list, "two"), sum(list, "three"));

Alternatively, mutate an initially empty instance in a loop:

var all = [a, b, c].reduce((obj, x) => {
    obj.one += x.one;
    obj.two += x.two;
    obj.three += x.three;
    return obj;
}, new myfunc(0, 0, 0));

Upvotes: 3

Related Questions