So I'm using JavaScript to make something to solve simple algebraic expressions. I've got everything for the math part done but I need to run a line of code again. So I've used a conditional branch to determine if the first side of the equation is equal to the second side. If it's equal then the value of the variable is given but if it isn't the same, then the variable is increased by one.
function Command() {
var FirstSide = document.getElementById("FirstLine").value;
var SecondSide = document.getElementById("SecondLine").value;
var evalLineOne = FirstSide;
var evalLineTwo = SecondSide;
var X = 1;
var MathLineOne = eval(evalLineOne);
var MathLineTwo = eval(evalLineTwo);
if (MathLineOne == MathLineTwo)
document.getElementById("Reply").innerHTML = X;
else {
X + 1;
}
So this is the code I've used. When using an algebraic expression where the value of X is not 1 the code simply doesn't work. I was assuming this was because I would need to rerun the code from the line of code which defines the value of "X". How would I go back to run this code?
Without making a lot of changes to your code, you could call the same function recursively like so:
var max = 9999999; //set this to whatever you want
function Command(X) {
if (typeof X === 'undefined') X = 1;
if (X > max) return;
var FirstSide = document.getElementById("FirstLine").value;
var SecondSide = document.getElementById("SecondLine").value;
var evalLineOne = FirstSide;
var evalLineTwo = SecondSide;
var MathLineOne = eval(evalLineOne);
var MathLineTwo = eval(evalLineTwo);
if (MathLineOne == MathLineTwo)
document.getElementById("Reply").innerHTML = X;
else {
Command(X+1);
}
}
Related
I'm trying to make an egg catching game and found some code snippets online and wanted them to work together so the points go up by one when two divs are colliding. I am getting this error Cannot access 'isColliding' before initialization. Also I don't know if the div collision works since I can't test it because of the error, thanks in advance for any help!
Code:
let points = $('#points');
let countpoints = 0;
let overlap = isColliding("#basket", "#egg6");
if (overlap) {
function EggHitsBasket() {
countpoints++;
points.text("points:" + countpoints);
}
}
let isColliding = function (div1, div2) {
let d1Offset = div1.offset();
let d1Height = div1.outerHeight(true);
let d1Width = div1.outerWidth(true);
let d1Top = d1Offset.top + d1Height;
let d1Left = d1Offset.left + d1Width;
let d2Offset = div2.offset();
let d2Height = div2.outerHeight(true);
let d2Width = div2.outerWidth(true);
let d2Top = d2Offset.top + d2Height;
let d2Left = d2Offset.left + d2Width;
return !(d1Top < d2Offset.top || d1Offset.top > d2Top || d1Left < d2Offset.left || d1Offset.left > d2Left);
};
you're calling isColliding before it's been defined, it's the same that would happen in the following code snippet:
let x = y * 2
let y = 42
you need to either declare isColliding before you call it. Or use of a function declaration
function isColiiding(div1, div2) { ... }
rather than a function expression
let isColliding = function (div1, div2) { ... }
The goal of this "counter" is to see how many different words are inside the "ToCount"string. To do that it makes ToCount an array and then iterates over the elements, checking if they already are there and if not, adding them there.
The ToCountArr2 remains empty after the loop and a length of 0 is being displayed. Why does that happen and what can I do about it?
I ran a debugger and saw that no elements are added to the second list, as if nothing appenned inside the "if" control if the i-th element of the first array already is inside the second array.
function counter(){
var ToCount = document.getElementById("demo").value; //the contents of a textbox
var ToCountArr1 = ToCount.split(" ");
var ToCountArr2 = new Array;
var i = 0;
var lengthToCountArr1 = ToCountArr1.length;
var wordToPush;
while (i < lengthToCountArr1){
if(ToCountArr2.includes(ToCountArr1[i] === false)) {
wordToPush = ToCountArr1[i];
ToCountArr2.push(wordToPush);
}
i = i + 1;
}
alert(ToCountArr2.length);
}
The issue is with this line if(ToCountArr2.includes(ToCountArr1[i] === false)). Here the braces need to be after ToCountArr1[i], where as this line ToCountArr1[i] === false) is checking whether that value in ToCountArr1 is true or false.
This line
if(ToCountArr2.includes(ToCountArr1[i] === false)) will be evaluated as
if(ToCountArr2.includes(true/false))
depending on result of ToCountArr1[i] === false)
function counter() {
var ToCount = document.getElementById("demo").value; //the contents of a textbox
var ToCountArr1 = ToCount.split(" ");
var ToCountArr2 = new Array;
var i = 0;
var lengthToCountArr1 = ToCountArr1.length;
var wordToPush;
while (i < lengthToCountArr1) {
if (ToCountArr2.includes(ToCountArr1[i]) === false) {
wordToPush = ToCountArr1[i];
ToCountArr2.push(wordToPush);
}
i = i + 1;
}
console.log(ToCountArr2.length);
}
counter()
<input type='text' id='demo' value='Test Values'>
You can minimize if (ToCountArr2.includes(ToCountArr1[i]) === false) { by replacing it with
if (!ToCountArr2.includes(ToCountArr1[i])) {
Your wordcount function should use a parameter so you can pass a string in. This means you can use the wordcount function on an any string, not just the "demo" element. Also, this is a good time to learn about Map -
const wordcount = (str = "") =>
{ const result =
new Map
for (const s of str.split(/ /))
if (s === "")
continue
else if (result.has(s))
result.set(s, result.get(s) + 1)
else
result.set(s, 1)
return Array.from(result.entries())
}
const prettyPrint = (value) =>
console.log(JSON.stringify(value))
<!-- pass this.value as the string for wordcount
-- wordcount returns a value that we could use elsewhere
-- prettyPrint displays the value to the console
-->
<input onkeyup="prettyPrint(wordcount(this.value))">
Run the code snippet and copy/paste the following line into the field -
this is the captain speaking. is this the commander?
You will see this output -
[["this",2],["is",2],["the",2],["captain",1],["speaking.",1],["commander?",1]]
Here is an working example. I think it will help you right way. Here I use indexOf to check the value exist on a array.
function counter(){
var ToCount = "I am string just for text.";//document.getElementById("demo").value; //the contents of a textbox
var ToCountArr1 = ToCount.split(" ");
var ToCountArr2 = new Array;
var i = 0;
var lengthToCountArr1 = ToCountArr1.length;
var wordToPush;
while (i < lengthToCountArr1){
if( ToCountArr2.indexOf(ToCountArr1[i]) == -1 ) {
wordToPush = ToCountArr1[i];
ToCountArr2.push(wordToPush);
}
i = i + 1;
}
alert(ToCountArr2.length);
}
counter();
I am using angular and plotly to plot either the raw data or a moving average. I have the moving average working but I am running into an issue with assigning variables. I retrieve an array of user objects which each have an x and y key with arrays associated with them.
$scope.init=function(){
$rootScope.page='companyResults';
$scope.isPlotlyDone = false;
$scope.moving = false;
var refresh = function () {
incidentService.dayWiseTripsByUser(...).then(function (plotArray){
$scope.unaffectedPlot = plotArray;
$scope.movingAveragePlot = allMoving(plotArray);
console.log($scope.unaffectedPlot[0].y);
console.log($scope.movingAveragePlot[0].y);
});
};
refresh();
}
Im that code block, I would expect that $scope.unaffectedPlot[0].y and $scope.movingAveragePlot[0].y would have different arrays since I ran the latter through the following set of functions. The curious thing is that both $scope variables are synced, so if I run the second through allMoving the unaffectedPlot variable also gets smoothed and neither get synced obviously if I don't call allMoving. What am I missing about Angular? What is a good way to have a moving average work with a toggle? My plan is to show one variable or the other depending on if a button is clicked.
var d3_numeric = function(x) {
return !isNaN(x);
}
var d3sum = function(array, f) {
var s = 0,
n = array.length,
a,
i = -1;
if (arguments.length === 1) {
// zero and null are equivalent
while (++i < n) if (d3_numeric(a = +array[i])) s += a;
} else {
while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
}
return s;
};
var movingWindowAvg = function (arr, step) {
return arr.map(function (_, idx) {
var wnd = arr.slice(idx - step, idx + step + 1);
var result = d3sum(wnd) / wnd.length; if (isNaN(result)) { result = _; }
return result;
});
};
var allMoving = function(pltArray) {
var movingArray = [];
pltArray.forEach(function(plot){
var oneMoving = plot;
oneMoving.y = movingWindowAvg(plot.y, 5);
movingArray.push(oneMoving);
});
return movingArray;
}
This actually isn't an angular issue. I had to test it some since I didn't see what was going on either.
When you wrote
oneMoving.y = blah
you were actually altering the contents of plot for each element and in turn altering the contents of plotArray unintentionally (since plot is an object)
So you are only creating a reference variable when you say 'var onMoving = plot' )
To outright solve your problem you can clone plot but that isn't so clean of a process
One easy yet dirty way is
JSON.parse(JSON.stringify(obj))
from this thread
I threw together a shotty example that captures what was going wrong for you
var array = [{one:1, two:2},{one:1, two:2},{one:1, two:2}],
copyArray = array,
newArr = doStuff(array)
function doStuff(a) {
var otherNewArr = []
a.forEach(function(ae) {
var aVar = ae
aVar.one = 5
otherNewArr.push(aVar)
})
return otherNewArr
}
console.log(copyArray,newArr)
And to fix it just replace
var aVar = ae
with
var aVar = JSON.parse(JSON.stringify(ae))
I'm building a game currently but I have a small problem with keeping the score. Basically I have an textfield that gets a random word input, then if someone clicks on the field or symbol containing the field then I want to check the random word input, if it's a correct word I want to update score textfield, if it's incorrect I want to update errors textfield.
For this I am using an if/else construction, the problem I have with it is that in my game every click only goes either in the if statement or if I change code then only the else, but it's not checking symbol for symbol, every time I click to see if it's an correct word or not. Here is the code I am using on the symbol.click symbol. My question is, am I doing anything wrong in the if/else statements or are my variable calling methods wrong. I have source files on request.
symbol.click:
var y = sym.getVariable("lijst");
var x = "bommen";
// if variables are a match then update score with 1
if (sym.getVariable("x") == sym.getVariable("y"))
{var score3 = sym.getComposition().getStage().getVariable("score1");
score3= score3 +=1;
sym.getComposition().getStage().$ ("scoreTxt").html(score3);
sym.getComposition().getStage().setVariable("score1", score3);
}
// else update error textfield with 1
else {
var fouten= sym.getComposition().getStage().getVariable("fouten1");
fouten= fouten +=1;
sym.getComposition().getStage().$ ("hpTxt").html(fouten);
sym.getComposition().getStage().setVariable("fouten1", fouten);
}
symbol.creationComplete
var words = ['bommen',
'dammen',
'kanonnen',
'dollen',
'bomen',
'feesten',
'lampen',
'voeten',
];
var lijst = words[Math.floor(Math.random() * words.length)];
sym.$("dynamicText").html(lijst);
//And my stage:
stage.creationComplete
// some different variables declarations
sym.setVariable("score1", 0);
sym.setVariable("fouten1", 0)
//var game = sym.getComposition().getStage();
var cirkels = [];
var test1 = "bommen";
var score2 = sym.getComposition().getStage().getVariable("score1");
var fouten = sym.getComposition().getStage().getVariable("fouten1");
var cirkelStart = {x:180,y:190};
var cirkelSpacing = {x:170,y:170};
function init(){
initPlayer();
spawnCirkels();
}
//this is for score and error updating
function initPlayer(){
sym.$("scoreTxt").html(score2);
sym.$("hpTxt").html(fouten);
}
// create symbols on a grid
function spawnCirkels(){
var cirkel;
var el;
var i;
var xPos = cirkelStart.x;
var yPos = cirkelStart.y;
var col = 0;
for(i = 0;i < 15;i++){
cirkel = sym.createChildSymbol("Cirkel", "Stage");
cirkel.play(Math.random() * 1000);
cirkels.push(cirkel);
el = cirkel.getSymbolElement();
el.css({"position":"absolute", "top":yPos + "px", "left":xPos + "px"});
xPos += cirkelSpacing.x;
col++;
if(col === 5){
col = 0;
yPos += cirkelSpacing.y;
xPos = cirkelStart.x;
}
}
}
init();
If anyone sees what I am doing wrong let me know!
Thanks for your help anyway!
My script is causing the browser to freeze and asking me to stop the script. Using firebug I can see the for loop is endlessly looping and not making any progress. Here's the loop:
for (var x = 1; x < 7; x++) {
var y = x; //to stop the value of x being altered in the concat further down
var questionidd = "mcq_question_id";
console.log("1 = " + questionidd);
var questionid = questionidd.concat(y); // mcq_question_id$ctr the question number
console.log("2 = " + questionid);
var mcqid = form[questionid].value; // the questions id on db
console.log("3 = " + mcqid);
var answerr = "mcq_question";
var answer = answerr.concat(y); // mcq_question$ctr the questions chosen answer
var chosenanswer = form[answer].value; // the answers value
console.log("4 = " + chosenanswer);
var amp = "&";
var equal = "=";
var questionide = questionid.concat(equal); // "mcq_question_id$ctr="
var questionida = amp.concat(questionide); // "&mcq_question_id$ctr="
var answere = amp.concat(answer, equal); // "&mcq_question$ctr="
if (x = 1) {
send.push(questionide, mcqid, answere, chosenanswer);
}
else {
send.push(questionida, mcqid, answere, chosenanswer);
}
}
Update - Fixed! Silly mistakes are the worst
if (x = 1) {
should be
if (x === 1) {
The === operator compares while the assignment operator = assigns. Many people make this mistake. :)
When the first loop runs, it sets x to zero, and does so infinitely until the process is terminated. That's why the loop doesn't stop.
if (x = 1) { should be if (x === 1) {
Consider switching to an IDE that catches simple programming errors like this.
Looks like you should have "if (x == 1)" instead of "if (x = 1)".
Your code repeatedly sets x to the value 1, rather than checking that it is equivalent to 1.