how can I remember my variable out if - javascript

How can I remember my variable tempValue outside if to give it as a parameter to other function? Because however it returns zero...
function rememberFirstOperand()
{
var rep1 = /[/|*|+|-]/;
var rep2 = /[0-9](?=[*|/|+|-])/;
var tempValue=0;
if (rep1.test(calculator.answer.value))
{
tempValue=calculator.answer.value;
calculator.answer.value='';
}
return tempValue;
}

Related

How to compare two variables and set a value of a third variable

I have this function I can't seem to get to work. I want it to compare two variables and set the value of a third variable.
var win_lose;
var this_roll = $('#past')[0].childNodes[9].textContent;
var last_roll = $('#past')[0].childNodes[9].textContent;
function compare() {
if (!(this_roll == last_roll)) {
win_lose = 'lose';
} else {
win_lose = 'win';
}
console.log(win_lose);
}
Did you actually call the function?
var this_roll = $('#past')[0].childNodes[9].textContent;
var last_roll = $('#past')[0].childNodes[9].textContent;
function compare(this_roll, last_roll) {
var win_lose; //added new variable here
if (this_roll != last_roll) {
win_lose = 'lose';
} else {
win_lose = 'win';
}
return win_lose;
}
var res = compare(this_roll, last_roll);
console.log(res);
I also rewrote your if statement, no need to check for equality then invert.
I would also pass parameters in to a function as I have.

Read foreach variable value outside the function

i have 2 functions where i have many variables stored . i want to read those variables outside the function as well. so i can read that value and apply if condition on that. please help.
And here are the functions,
var dynamicFormObject = new dynamicObject(jsonDataModel);
function dynamicObject(jsonData) {
this.formId = jsonData[0].formName;
console.log(this.formId);
this.formType = jsonData[0].formType;
this.formLayout = jsonData[0].formLayout;
this.sectionCount = jsonData[0].sections.length;
this.getSectionDetails = sectionDetails(jsonData[0].sections);
this.formRows = getSetionFieldDetails(jsonData[0].sections);
this.formFields = getContainedFields(jsonData[0].sections);
this.getNoOfSections = function(jsonData) {
return jsonData[0].sections.length;
};
}
function sectionDetails(sectionData) {
var sectionDetails = [];
if (sectionData.length > 0) {
sectionData.forEach(function(item) {
sectionDetails.push({
sectionId: item.sectionId,
sectionName: item.sectionName,
sectionLayout: item.sectionLayout
});
});
return sectionDetails;
} else {
return "Error";
}
}
sectionDetails(jsonDataModel);
console.log(sectionDetails[0].sectionLayout);
if($scope.entity[0].sections[0].sectionId === 1 && $scope.entity[0].sections[0].sectionLayout == "linear_layout_vertical"){
if(dynamicFormObject.formLayout == "linear_layout_horizontal"){
console.log("sadasd");
var newdiv = document.createElement("div");
console.log(newdiv);
newdiv.setAttribute('horizontal', '');
newdiv.setAttribute('layout', '');
newdiv.className('col-md-12');
document.body.appendChild(newdiv);
}
It's not possible to access a variable declared from within a function closure from outside it's function closure, however, you can declare a variable outside the function and only use/update it within the function, and the results of that use/update will be available outside the function.
var x;
function setX(){
x = 6;
}
setX();
console.log(x) // 6

Trying to understand closures (JavaScript)

function myFunc(inputFunc){
var called = false;
return function() {
if (!called) {
called = true;
var storedResult = inputFunc();
return storedResult;
}
else
return storedResult;
};
}
In the above code, I don't understand what purpose it serves to have the if-else statement returned in a function. Wouldn't it be the same effect if I just had the following instead?
function myFunc(inputFunc){
var called = false;
if (!called) {
called = true;
var storedResult = inputFunc();
return storedResult;
}
else
return storedResult;
}
Wouldn't it be the same...
Not really, the outer function returns a function, enclosing the called variable in it's scope so it doesn't change in later calls
Here's how the first code snippet would work
var instance = inputFunc();
var storedResult = instance(); // returns the result
var runItAgain = instance(); // probably returns `undefined`
Your second version wouldn't do any of that, it would just be
var storedResult = inputFunc(); // result
var runItAgain = inputFunc(); // result again, the "called" variable is always false
In other words, the first version returns the result once, and only once, here's a snippet
function myFunc(inputFunc) {
var called = false;
return function() {
if (!called) {
called = true;
var storedResult = inputFunc();
return storedResult;
} else
return storedResult;
};
}
var instance = myFunc(function() {
return 'result';
});
var log = [];
log.push( instance() ); // result
log.push( instance() ); // undefined
log.push( instance() ); // undefined
log.push( instance() ); // undefined
document.body.innerHTML = '<pre>' + JSON.stringify(log, null, 4) + '</pre>';

Simplify the code by using cycle function

I have multiply functions which are using the same cycle code and i'm wondering is it possible to simplify the code by having one cycle function so i could execute the code just by calling wanted function names.
Now:
for(var i=0;i<all;i++){ someFunction(i) }
Need:
cycle(someFunction);
function cycle(name){
for(var i=0;i<all;i++){
name(i);
}
}
I tried to do this by using "window" and i get no error but the function is not executed.
var MyLines = new lineGroup();
MyLines.createLines(); // works
MyLines.addSpeed(); // doesn't work
var lineGroup = function(){
this.lAmount = 5,
this.lines = [],
this.createLines = function (){
for(var i=0,all=this.lAmount;i<all;i++){
this.lines[i] = new line();
}
},
this.addSpeed = function (){
// no error, but it's not executing addSpeed function
// if i write here a normal cycle like in createLines function
// it's working ok
this.linesCycle("addSpeed");
},
this.linesCycle = function(callFunction){
for(var i=0,all=this.lAmount;i<all;i++){
window['lineGroup.lines['+i+'].'+callFunction+'()'];
}
}
}
var line = function (){
this.addSpeed = function (){
console.log("works");
}
}
window['lineGroup.lines['+i+'].'+callFunction+'()'];
literally tries to access a property that starts with lineGroups.lines[0]. Such a property would only exist if you explicitly did window['lineGroups.lines[0]'] = ... which I'm sure you didn't.
There is no need to involve window at all. Just access the object's line property:
this.lines[i][callFunction]();
i get no error but the function is not executed.
Accessing a non-existing property doesn't generate errors. Example:
window[';dghfodstf0ap9sdufgpas9df']
This tries to access the property ;dghfodstf0ap9sdufgpas9df, but since it doesn't exist, this will result in undefined. Since nothing is done with the return value, no change can be observed.
Without a name space use:
window["functionName"](arguments);
SO wrap it up and use it thus:
cycle(someFunction);
function cycle(name){
for(var i=0;i<all;i++){
window[name](i);;
}
}
With a namespace, include that:
window["Namespace"]["myfunction"](i);
Note that this is likely a bit of overkill but using a function to make a class object (you can google the makeClass and why it is/could be useful) you can create instances of the object.
// makeClass - By Hubert Kauker (MIT Licensed)
// original by John Resig (MIT Licensed).
function makeClass() {
var isInternal;
return function (args) {
if (this instanceof arguments.callee) {
if (typeof this.init == "function") {
this.init.apply(this, isInternal ? args : arguments);
}
} else {
isInternal = true;
var instance = new arguments.callee(arguments);
isInternal = false;
return instance;
}
};
}
var line = function () {
this.addSpeed = function () {
console.log("works");
};
};
var LineGroup = makeClass();
LineGroup.prototype.init = function (lineNumber) {
this.lAmount = lineNumber?lineNumber:5,
this.lines = [],
this.createLines = function (mything) {
console.log(mything);
var i = 0;
for (; i < this.lAmount; i++) {
this.lines[i] = new line();
}
},
this.addSpeed = function () {
console.log("here");
this.linesCycle("addSpeed");
},
this.linesCycle = function (callFunction) {
console.log("called:" + callFunction);
var i = 0;
for (; i < this.lAmount; i++) {
this.lines[i][callFunction]();
}
};
};
var myLines = LineGroup();
myLines.createLines("createlines");
myLines.addSpeed();
//now add a new instance with 3 "lines"
var newLines = LineGroup(3);
newLines.createLines("createlines2")
console.log("addspeed is a:" + typeof newLines.addSpeed);
console.log("line count"+newLines.lAmount );
newLines.addSpeed();

Create an object with modified versions of all methods in a source object [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I want to create an object that has modified versions of all of the methods in a source object, but I'm having trouble using for...in.
If this is my source object:
var raw = {};
raw.add = function(a,b){return a + b;}
raw.sub = function(a,b){return a - b;}
raw.neg = function(a){return -a;}
raw.sqrt = function(a){return Math.sqrt(a);}
It works if I recreate the list of properties in an array of strings:
var mod2 = Object.create(raw);
var proplist = ["add", "sub", "neg", "sqrt"];
proplist.forEach(function(prop){
mod2[prop] = function(){
var arglist = [].slice.apply(arguments);
var out = [];
if(arglist.length == 1){
[].concat(arglist[0]).forEach(function(d){ out.push(raw[prop](d)); });
}
else if(arglist.length == 2){
[].concat(arglist[0]).forEach(function(d1){
[].concat(arglist[1]).forEach(function(d2){
out.push(raw[prop](d1,d2));
})
});
}
return out;
}
});
But my attempt to use for..in doesn't work, all of the methods in the new object will do "sqrt":
var modified = Object.create(raw);
for(prop in raw){
modified[prop] = function(){
var arglist = [].slice.apply(arguments);
var out = [];
if(arglist.length == 1){
[].concat(arglist[0]).forEach(function(d){ out.push(raw[prop](d)); });
}
else if(arglist.length == 2){
[].concat(arglist[0]).forEach(function(d1){
[].concat(arglist[1]).forEach(function(d2){
out.push(raw[prop](d1,d2));
})
});
}
return out;
}
}
What is the best way to iterate through the methods automatically?
The issue with your second implementation is that you are using prop in your new method (which will be called sometime later), but the for loop that creates prop has already run to completion by the time that method is called sometime later so prop is not the right value any more (it will always be the last property). I fixed that in my implementation by capturing prop in an IIFE (immediately invoked function expression) so it would be frozen separately for each pass through the for loop. Your first implementation doesn't have that problem because you're using .forEach() on the array of properties which uses a callback function which captures the value of prop for you automatically into a closure.
So here's the result with these changes to your implementation:
Add an IIFE to freeze the value of prop for use in the new methods.
Add an extra check to make sure the methods we're copying are not inherited and are functions.
Initialized raw to a plain object as I don't see any reason to use Object.create() here.
The code:
var raw = {};
raw.add = function(a,b){return a + b;}
raw.sub = function(a,b){return a - b;}
raw.neg = function(a){return -a;}
raw.sqrt = function(a){return Math.sqrt(a);}
var modified = {};
for (prop in raw) {
if (raw.hasOwnProperty(prop) && typeof raw[prop] === "function") {
(function (prop) {
modified[prop] = function () {
var arglist = [].slice.apply(arguments);
var out = [];
if (arglist.length == 1) {
[].concat(arglist[0]).forEach(function (d) {
out.push(raw[prop](d));
});
} else if (arglist.length == 2) {
[].concat(arglist[0]).forEach(function (d1) {
[].concat(arglist[1]).forEach(function (d2) {
out.push(raw[prop](d1, d2));
})
});
}
return out;
}
})(prop);
}
}
Working demo: http://jsfiddle.net/jfriend00/5LcLh/
<script>
var raw = {};
raw.add = function () { console.log('add default method'); }
raw.sub = function () { console.log('sub default method'); }
raw.neg = function () { console.log('neg default method'); }
raw.sqrt = function () { console.log('sqrt default method'); }
console.log('*****************');
console.log('before modifying');
console.log('*****************');
raw.add();
raw.sub();
raw.neg();
raw.sqrt();
var proplist = ["add", "sub", "neg", "sqrt"];
console.log('*****************');
console.log('after modifying');
console.log('*****************');
console.log('');
var modified = Object.create(raw);
for (prop in proplist) {
if (prop == 0)
console.log('rewriting methods and calling methods inside loop................');
modified[proplist[prop]] = function () { console.log(proplist[prop] + ' method modified, ' + proplist.length + ' argument passed') }
modified[proplist[prop]]();
}
console.log('');
console.log('trying call methods after loop is done................');
modified.add();
modified.sub();
modified.neg();
modified.sqrt();
console.log('...it is becaouse "prop" variable in loop holding last count number ' + prop);
</script>
thanks to arnold.NET.JS's response clarifying the problem, I see that closure is one way to do it:
var raw = {};
raw.add = function(a,b){return a + b;}
raw.sub = function(a,b){return a - b;}
raw.neg = function(a){return -a;}
raw.sqrt = function(a){return Math.sqrt(a);}
var mod = Object.create(raw);
for(prop in raw){
mod[prop] = (function(){
var propname = prop;
function f(){
var arglist = [].slice.apply(arguments);
var out = [];
if(arglist.length == 1){
[].concat(arglist[0]).forEach(function(d){ out.push(raw[propname](d)); });
}
else if(arglist.length == 2){
[].concat(arglist[0]).forEach(function(d1){
[].concat(arglist[1]).forEach(function(d2){
out.push(raw[propname](d1,d2));
})
});
}
return out;
}
return f;
})();
}

Categories

Resources