Variable not persisting when using a constructor - javascript

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

Related

Write a higher-order function, checkConsistentOutput()

This function should have two parameters: a function and a value. It should call the argument function with the value two times. If the callback function produces the same result twice, it should return the result of the function call, otherwise, it should return the string 'This function returned inconsistent results'
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong :( ');
}
}
};
const addTwo = num => num + 2;
const timeFuncRuntime = funcParameter => {
let t1 = Date.now();
funcParameter();
let t2 = Date.now();
return t2 - t1;
};
// Write your code below
const time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes);
const checkConsistentOutput(func, val) => {
let checkOne = func(val);
let checkTwo = func(val);
if (checkOne === checkTwo){
return checkOne;
} else {
return 'This function returned inconsisent results'
}
}
I'm getting the error SyntaxError: Missing initializer in const declaration. please help me understand.
I'm seeing an error in the last const declaration that appears to be because it's missing an '='.
const checkConsistentOutput(func, val) => {
...
}
const checkConsistentOutput = (func, val) => {
...
}

Execute Multiple functions in a function

function executeActions(param)
{
if((param != undefined) && (param.length > 0))
{
for(i=0; i < param.length; i++)
{
//eval like function
param[i]();
}
}
}
function clearFields()
{
...
}
function showAbs(param)
{
if(param == 'insert')
{
...
}
else if(param == 'update')
{
...
}
else
{
...
}
}
$("#clearButton").click(function(event)
{
//var functions = ["clearFields()","showAbs('insert')"];
var a = showAbs('insert');
var functions = [clearFields, a];
executeActions(functions);
});
Hello everyone!
How can I execute some functions with parameters in a row in a set of instructions like i've showed above?
If they don't have any parameters, then the functions execute like in chain, but, if one or more of them uses
some parameters, it stops with the error: "param[i] is not a function".
Maybe if you have another elegant solution for this code, i'd appreciate if you share with us.
Thank you all in advance!
You can use partial application for this. Partial application means that you take a given function and fix one or more parameters to it. Example
function sum(a, b){
return a + b;
}
function product(a, b){
return a * b;
}
function doSomething(){
// do something
}
function runFunctions(funcs){
for(var i = 0;i<funcs.length;i++){
funcs[i]();
}
}
var mySum = function(){
return sum(5, 6);
}
var myProduct = function(){
return product(2, 3);
}
runFunctions(mySum, myProduct, doSomething);
The above is using ES 5 syntax. You could make this a bit more concise using ES 6 syntax:
const sum = (a, b) => a + b;
const product = (a, b) => a * b;
const doSomething = () => // do something
const runFunctions = funcs => {
for(func of funcs)
func();
}
var mySum = () => sum(5, 6);
var myProduct = () => product(2, 3);
runFunctions(mySum, myProduct, doSomething);
or you could use the bind function to take care of fixing the vars:
const sum = (a, b) => a + b;
const product = (a, b) => a * b;
const doSomething = () => // do something
const runFunctions = funcs => {
for(func of funcs)
func();
}
runFunctions(sum.bind(null, 5,6), myProduct.bind(null, 2,3), doSomething);
For me a way you want to achieve may be not readable for other developers.
You may create a function that will group all your function executions like:
function groupedFunctions{
return {
A: funcA(param),
B: funcB(param),
C: funcC(param)
}
}
function executeActions(funcObj, params) {
funcObj.A(params.a);
funcObj.B(params.b);
}
let params = {a: 1, b:2}
executeActions(groupedFunction(), params)

Convert foreach into map function in javascript

This is my function in foreach loop for creating object which has property and value as word and its count, but i want to convert it in map according to es6
function harmlessRamsonNote(noteText,magazineText)
{
var noteArr = noteText.split(' ');
var magazineArr = magazineText.split(' ');
var magazineObj = {};
magazineArr.forEach(word => {
if(!magazineObj[word])
{
magazineObj[word] = 0;
}
magazineObj[word]++;
});
console.log(magazineObj);
};
magazineArr.map((word, index, array) => {
!magazineObj[word] ? magazineObj[word] = 0 : magazineObj[word]++;
})
map will return an new item for each item. Instead you can use reduce.
const magazineObj = magazineArr.reduce((acc,word) => {
acc[word] = (acc[word] || -1) + 1;
}, {});

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

Categories