Addition of two or more functions in javascript - 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.

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));

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

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()

Related

Variable not persisting when using a constructor

So I'm using a constructor like this
const RPNCalculator = function () {
let methods = {
numberList: [],
calc: 0,
push(num) {
this.numberList.push(num);
},
plus() {
for (let i = 0; i <= this.numberList.length; i++) {
console.log('before:' + this.calc);
this.calc = this.calc + this.numberList[i];
}
console.log('after:' + this.calc);
this.numberList = [];
}
};
return methods;
}
const rpnCalculatorInstance = new RPNCalculator;
The fist console.log prints correctly and adds the elements but the second console.log prints NaN. I've used this pattern before with Object.create but for some reason the this.calc variable isn't persisting when using a constructor.
Any help is appreciated!
you can use reduce to sum up an array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
run snippet below
class RpnCalculator{
constructor(){
this.numberList = [];
this.push = (num) => { this.numberList = [...this.numberList, num ]}
this.sum = () => {return this.numberList.reduce(( a, c) => a + c, 0);}
}
}
const rpnCalculator = new RpnCalculator();
rpnCalculator.push(1)
rpnCalculator.push(2)
rpnCalculator.push(3)
console.log(rpnCalculator.sum());
Apparently with the dataset I was given the last item in the array was an undefined element. I fixed it by using
if (typeof (this.numberList[i]) === 'number') {
console.log('before:' + this.calc);
this.calc = this.calc + this.numberList[i];
}

Javascript: making functions at runtime

update
solution works in foreach loop but not in for loop
function x(number){
return number - 10;
}
var i = 0
var runtimefunctions = {};
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
for (var key in allLevels) {
runtimefunctions[i] = function() { return x(i); };
i++;
};
console.log(runtimefunctions[1]()); // -6
console.log(runtimefunctions[2]()); // -6
console.log(runtimefunctions[3]()); // -6
tried hard to make functions but it's first time to create such thing so cant understand the proper way...
I have a function..
function x(number){
return number - 10;
}
runtimefunctions = {};
now I have a loop to run
[1,2,3].forEach(function(y){
//here I want to create a function.. which will make a function x(y) -- like this
runtimefunctions[x] = new Function("return function x_" + levelIterator + "(levelIterator){ console.log(levelIterator); x(" + y + ") }")();
});
so basically..want to make functions like this.
runtimefunctions= {
"1": x(1),
"2": x(2),
and so on
}
Is this what you need?
function x(number){
return number - 10;
}
var runtimefunctions = {};
[1,2,3].forEach(function(y){
runtimefunctions[y] = function() { return x(y); };
});
console.log(runtimefunctions[1]()); // -9
console.log(runtimefunctions[2]()); // -8
console.log(runtimefunctions[3]()); // -7
To satisfy your next (for-in) requirement, you need to closure the index variable with additional function call:
var runtimefunctions = {}, i = 0;
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
for (var key in allLevels) {
runtimefunctions[i] = function(index){ return function() { return x(index); } }(i++);
};
It is much easier.
For example:
const createFunctionWith = (x) => {
return (param) => console.log(x, param)
}
let a = [1,2,3].map(x => createFunctionWith(x));
console.log(a[1]("bebe")); // 2, "bebe"
https://jsfiddle.net/muLxoxLd/
You could do something like this
// Found in your code
var x = (a) => {
console.log(a)
};
var runtimefunctions = {};
[1, 2, 3].forEach(function(y) {
//Create a function with a parameter named "levelIterator"
runtimefunctions[y] = Function("levelIterator", "{ console.log(levelIterator); x(" + y + ") }");
});
runtimefunctions[1]('test')

JavaScript : what does it mean to have brackets () after array[]?

I am new to JS, and I have read a code that contains this line.
this.myArray[index](this._sender, args);
I wonder what it means?
It means that this array item is a function, and it is being called with arguments this._sender and args.
In this example, I declare an array, push a single-argument function to it, and call it.
var arr = [];
arr.push(function(str) {
document.body.innerHTML = "Hey, " + str;
});
arr[0]("Your name");
that means that the myArray[index] is the element of myArray that is function that is why it requires 2 arguments.
It is similar to following snippet:
var myClass = function () {
this._a = 5;
var index = arguments[0] || 0;
this.myArray = [
function (a, b) {
console.log(a, b);
},
function (a, b) {
console.log(a, b);
}
];
this.myArray[index](this._a, arguments);
};
var obj = new myClass(1, 2, 3);//5 [1, 2, 3]
In JavaScript, functions are first class objects so they can be passed around/referenced, stored, and accessed like any other value.
var myArray = [];
var myFunction = function(name) {
console.log("Hello, " + name + "!");
};
myFunction('World');
myArray[0] = myFunction;
myArray[0]('again');
function addDefault(func, defaultValue) {
return function(name) {
name = name ? name : defaultValue;
func(name);
}
}
var myFunctionWithDefault = addDefault(myFunction, 'stranger');
myFunctionWithDefault();
myFunctionWithDefault('goodbye');
JSBin: http://jsbin.com/wubuye/edit?js,console

How to merge these complex JavaScript array objects?

Can someone help me to do these example?
var a = ["17","18"];
var b = ["1","1","1"];
I need an output below:
var c = [17:111,18:111]
var a = ["17","18"];
var b = ["1","1","1"];
var i=0;
var ConcateC="";
for(i=0;i< b.length;i++)
{
ConcateC +=b[i];
}
var c=[];
for(i=0;i< a.length;i++)
{
c[i]=a[i] + ":" + ConcateC;
alert(c[i]);
}
You can join the values of b together, then use map to create a new array from the indices of a:
var a = ["17","18"];
var b = ["1","1","1"];
var bValue = b.join("");
var c = a.map(function(currentValue) {
return currentValue + ":" + bValue;
});
console.log(c); // ["17:111","18:111"]

Dynamically generated object not working as parameter to .css()

I have this function:
function myfunc(obj, properties, value) {
$.each(properties, function(i, key) {
var a = '-webkit-border-' + key + '-radius';
var b = '-moz-border-radius-' + key.replace(/\-/g, '');
var c = 'border-' + key + '-radius';
var z = value+'px';
obj.css({a : z, b: z, c: z});
});
}
Called like this:
myfunc($tab, ['top-left', 'top-right'], defaults.tabRounded);
Note that if I replace the obj.css line with:
obj.css({'border-top-right-radius': value+'px'});
It works as intended. Yet the values of a, b, c are completely correct.
What is going on?
The keys of an object literal in JavaScript are strings, not variables. If you do not quote them yourself, they are auto-quoted. So if you write
var a = {b: 1};
it's the same as if you had written
var a = {'b': 1};
You have to use [] to set keys dynamically.
var a = {};
a[b] = 1;
In this case modify your function to
function myfunc(obj, properties, value) {
$.each(properties, function(i, key) {
var a = '-webkit-border-' + key + '-radius';
var b = '-moz-border-radius-' + key.replace(/\-/g, '');
var c = 'border-' + key + '-radius';
var z = value+'px';
var css = {};
css[a] = css[b] = css[c] = z;
obj.css(css);
});
}

Categories