Argument in recursive function changes itself somehow - javascript

So, I have to find all possible cycles in not directed graph, that starts (and ends) at chosen vertex.
I have written an algorithm for it in js: jsfiddle
But faced very, very weird problem: in my recursive function, argument changes itself somehow! But I dont even touch it! Pls help me, I am suffering with this bug for 16 hours already! :(
I thinkm that this arguments is changed by this code:
cycle.push(vertex);
But it should not! Becuase in his visibility area the global cycle variable must be overwritten by local one!

Here's the issue:
var newCycle = cycle;
You're not cloning it, you're just giving the same object a different name. Try:
var newCycle = cycle.slice(0);

Related

JavaScript Variable calls function, but stays undefined

I'm extremely new to JavaScript and am attempting to make a very simple game of 'Rock, Paper, Scissors' that is played through the console.
Here is a jsfiddle.net link to the full thing.
The main issue so far is that, every single round, the game will result in a Tie (another one is that incorrect inputs in humanTurn() lead to an error further down the line, but that's not relevant to this topic which I feel is more pressing).
Both humanTurn() and computerTurn() seem to work fine when called individually, however when called within gameRound(), the two console.log()'s (lines 36 and 38) don't seem to be returning a value of any kind, and in the console these show up as ƒ toLocaleUpperCase() { [native code] }. I tried searching for what this could mean, and the only conclusion I've been able to come up with so far is that no value is actually being stored inside of the two variables, AIChoice and HUChoice, and I cannot fathom a reason for why this would be happening.
Any and all help is greatly appreciated!
computerTurn().toLocaleUpperCase and userTurn().toLocaleUpperCase are both functions and since they are on the String prototype, they are both the same function. If you compare them, they will always be equal.
You need to actually call the function in order to get the values you want:
let AIChoice = computerTurn().toLocaleUpperCase();
console.log(AIChoice);
let HUChoice = humanTurn().toLocaleUpperCase();
console.log(HUChoice);

Javascript: Array not shifting, multiple setTimeout functions (JSON)

I'm really stuck on this javascript question!
So I'm making a web page that will be completely animated (so it can be used for display for example in a television). That animation will be configurable by the user (stored in a database).
Right now, I've already made the code to store the configuration and to get the configuration (I do an AJAX call and save the configuration in an array of json objects) and everything is as it should be.
The problem is in the animation in which I go through the array and use setTimeout function to create animations. To iterate through the array I rotate it
(I use array.push(array.shift()) according to the answer here).
The first time the intervalmaster function is used, everything goes according to plan, but when the function is called again I need to rotate the array once more (because of the last animation) and the array just doesn't rotate!
Bellow I've left a portion of the code that I'm using that reproduces the problem I'm getting. I've also added the array jsonanima with some possible values (In reality the array is probably much bigger and with higher values).
I really don't understand what is happening, I've also considered that this could be a problem of the multiple setTimeout functions because I've read somewhere (couldn't find the link, sorry!) that is not really advised to use multiple setTimeout.
If that's the case is there any other way to do this?
Thank you in advance!
EDIT: Thanks to the comment from mplungjan I've realized that if change the console.log(jsonanimate) to console.log(JSON.stringfy(jsonanima)) it outputs the correct values (the json array rotated). This got me even more confused! Why do I need to JSON.stringfy to get the array in the correct order?!
Anyway, can't test this with the full code now as I'm not in the office, tomorrow I'll give more feedback. Thank you mplungjan.
EDIT2: Finally solved my problem! So the thing was the call to the function recursivegroup (recursivegroup(0);), this call was made before I rotated the array, so when restarting the animation the array would still have the incorrect values and every sub-sequential value was wrong.
A special thanks to mplungjan and trincot for the comments that helped me debug this problem.
Bellow I leave the code corrected so anybody with the same problem can check it out.
jsonanima=[{"VD":5,"A":10,"diff":0.25},{"L":7,"IE":8,"diff":0.25}];
function intervalmaster(flag){
function recursivegroup(index)
{
if(index==0)
{
//animateeach(jsonanima,0);
}
setTimeout(function(){
//HERE IT WORKS
jsonanima.push(jsonanima.shift());
console.log(JSON.stringify(jsonanima));
//animateeach(jsonanima,0);
//removed the if statement, since it was irrelevant as mplungjan noted
recursivegroup(index+1);
},(jsonanima[0]['diff'])*60*1000);
}
//Changed this
//recursivegroup(0);
var mastertime=0;
for(var key in jsonanima)
{
mastertime+=(jsonanima[key]['diff']);
}
console.log(mastertime,flag);
console.log(JSON.stringify(jsonanima));
if(flag==true)
{
jsonanima.push(jsonanima.shift());
console.log(JSON.stringify(jsonanima));
}
//changed to here
recursivegroup(0);
masterinterval=setTimeout(function(){intervalmaster(true)},mastertime*60*1000);
}
intervalmaster(false);

"in" operator showing functions in javascript

in my code I was always doing
for(i in vector)...
and it always worked, but the problem is that it somehow changed and now my for shows all the values but also the properties, like "remove" that is a function, and it is breaking my whole code.
I don't know why it suddenly changed, because I didn't do anything and I'm getting crazy with this already.
Do you guys know what is happening with my application?
Another thing is that the code only get this problem on my computer.
If I clone my repository again and try it works for while but then starts the problem again.
Thank you.
The in operator has always had this behaviour. Just check that the property exists directly on the object instead of on the prototype:
for (var i in vector) {
if (vector.hasOwnProperty(i)) {
// Property exists on object
}
}
That should solve your issues.
Tom

google script assining variable bug

I've noticed strange bug while setting a new value to a variable. Unfortunately the Value has been copied to a different variable as well. Do you have an idea what is going on here?
Here are some screen shots while debugging. One just before setting the new value and one just after. You can see how automatically the value has been copied to 2 different variables.
Here is the file if you want to check it yourself:
docs.google.com/spreadsheets/d/17L7KDVteaYUuBE8v5jRRUGBBHa5_Dg6dH0eQ8oDTde4/edit?usp=sharing
Thanks in advance guys
This is not a bug.
Assigning arrays to variables happens by reference (to a memory location) in JavaScript and most other programming languages.
Consider this simplified example
a=[1];
b=a;
b[0]=2;
a is now [2]
To assign a copy you need to create a copy for example using slice
c=a.slice();
c[0]=3;
a will now still be [2] and c will be [3].
So try
red = temp[i].slice();

Performance: Which of these examples of code is faster and why?

$('#element').method();
or
var element = $('#element');
element.method();
Without using a profiler, everyone is just guessing. I would suspect that the difference is so small it isn't worth worrying about. There are small costs to the second above the first like having to preform a lookup to find 'var element' to call the method on, but I would have thought finding '#element' and then calling the method is far more expensive.
However, if you then went on to do something else with element, the second would be faster
//Bad:
$('#element').foo();
$('#element').bar();
//Good:
var e = $('#element');
e.foo();
e.bar();
If you were using a loop where the value of $('#element') was used a lot, then caching it as in the 2nd version before the loop would help a lot.
For just this small snippet, it makes little difference.
Lookups via id (#) are pretty fast. I just tested your scenario on a small page with 2 div tags. Here is the code i used
var x = $("#div1");
var y = $("#div2");
var z = $("#div1");
every lookup took about 0.3ms on my laptop. The 2nd lookup for div1 executed the same internal jQuery methods as the first - indicating that there is no caching of already looked up objects
Performance becomes a bigger problem when you use other selectors like classname or more advanced jQuery selectors. I did some analysis on jQuery Selector Performance - check it out - hope it is helpful.
If you run only this code, no one should realy be faster. The second one might need more memory (because of the additional variable created).
If you want to be sure, why not test it yourself using a small selfwritten benchmark?
I think $('#element').method(); does not need as much memory as
var element = $('#element');
... because you bind #element to a variable.
Juste fore funne
\Indifferent:
$('#element').foo().bar();

Categories

Resources