Unexpected token ; when defining Boolean variable - javascript

I am setting up a TF2 trading bot that can price check. I get an error when defining a boolean for if it is priced in keys or not.
I have tried just replacing isKeys with data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys" in the if statement but get an error for the closing bracket in the if statement.
var data = {
};
var currencies = {
};
requestify.get('https://backpack.tf/api/IGetPrices/v4?raw=1&since=0&key=5cf17c256780725011449df2')
.then(function(response) {
data = response.getBody().response.items;
console.log(data["Australium Tomislav"].prices["11"].Tradable.Craftable);
}
);
requestify.get('https://backpack.tf/api/IGetCurrencies/v1?key=5cf17c256780725011449df2')
.then(function(response) {
currencies = response.getBody().response.currencies;
}
);
function toRef(keys, high) {
if (high) {
if (currencies.keys.price.value_high != undefined){
return currencies.keys.price.value_high * keys
} else {
return currencies.keys.price.value * keys
}
} else {
return currencies.keys.price.value * keys
}
}
function getPrice(item, high) {
var name = item.market_name;
var quality = item.tags[0].name;
var baseName = name.replace(quality + " ", "");
var qualityId = itemQualities[quality];
var isCraftable = true;
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys"; // Error here
for (i = 0;i < item.description.length;i++) {
if (item.description[i].value == '( Not Usable in Crafting )') {
isCraftable = false;
}
}
if (high) {
if (isKeys) {
return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high], true);
} else {
return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high];
}
} else {
if (isKeys) {
return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value], false);
} else {
return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value];
}
}
}
`
G:\BOT\bot.js:106
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys";
^
SyntaxError: Unexpected token ;
is the error I get

TL;DR: You are missing a ] on the erred line. And you have extra ] on the below if(high){...} lines.
You are missing a square bracket ] in the line,
var isKeys = ... as the other answers suggest.
Now, we don't know the data structure so it can be,
data[baseName]
.prices[qualityId.toString()]
.Tradable[craftable[isCraftable.toString()][0].currency*]*
or
data[baseName]
.prices[qualityId.toString()]
.Tradable[craftable[isCraftable.toString()][0]*]*.currency
But Also,
You have extra Square braces on the lines,
if (high) {
if (isKeys) {
/*--here>>*/return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high, true);
} else {
/*--here>>*/return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high;
}
} else {
if (isKeys) {
/*--here>>*/ return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value, false);
} else {
/*--here>>*/return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value;
}
}
Again we don't know the exact data structure.

You're missing a square bracket for Tradable
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()]][0].currency == "keys";

In that line a square-bracket-close (]) is missing.
Your line is:
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys"; // Error here
You open a bracket at .Tradable[ but it isn't closed until the end of that line.
The compiler expects a ] but finds a ;.
I am not familar with the API you are using but I suppose the following would fix the error:
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys"]; // << Notice the bracket before your semicolon

Related

Access array in if statement

I have JavaScript calculator wherein I have defined two arrays as follows:
var degInc, degArr = [];
var radInc, radArr = [];
var PI = Math.PI;
var radStart = (-91*PI/2), radEnd = (91*PI/2);
for (degInc = -8190; degInc <= 8190; degInc+=180) {
degArr.push(degInc);
}
for (radInc = radStart; radInc <= radEnd; radInc+=PI) {
var radIncFixed = radInc.toFixed(8);
radArr.push(radIncFixed);
}
to be used in conjunction with the tangent function (below) so as to display a value of Undefined in an input (HTML below) should the user attempt to take the tangent of these values (I have included other relavent function as well):
Input -
<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/>
Functions -
function tan(form) {
form.display.value = trigPrecision(Math.tan(form.display.value));
}
function tanDeg(form) {
form.display.value = trigPrecision(Math.tan(radians(form)));
}
function radians(form) {
return form.display.value * Math.PI / 180;
}
with jQuery -
$("#button-tan").click(function(){
if (checkNum(this.form.display.value)) {
if($("#button-mode").val() === 'DEG'){
tan(this.form); // INSERT OTHER 'if' STATEMENT HERE FOR RAD ARRAY
}
else{
tanDeg(this.form); // INSERT OTHER 'if' STATEMENT HERE FOR DEG ARRAY
}
}
});
I would like to incorporate an array check within the .click function such that if the user input is contained in the array (degArr or radArr depending on the mode), the calculator returns Undefined. Now, I know how to display Undefined in the input display ($('#disp').val('Undefined')), but I cannot figure out how to configure an if statement that checks the relevant array. Is there a way to do so within the #button-tan function where I have commented?
Loop through the arrays on click and set a variable if you find a matched value.
You can do something like this:
$("#button-tan").click(function(e) {
e.preventDefault();
var userInput = $('#disp').val();
var buttonMode = $('#button-mode').val();
var displayVal = '';
if (buttonMode === 'DEG') {
var radFound = false;
radArr.forEach(function(item) { // changed from degArr
if (item === userInput) {
radFound = true;
}
if (radFound) {
displayVal = 'undefined';
} else {
tan(this.form);
}
});
} else {
var degFound = false;
degArr.forEach(function(item) {
if (item === userInput) {
degFound = true;
}
if (degFound) {
displayVal = 'undefined';
} else {
tanDeg(this.form);
}
});
}
});
You could create a simple object of a Calculator class, which keeps a reference to these arrays, and use like this. I changed some methods to receive the input as parameter rather than form.
$(function () {
function Calculator()
{
var degInc;
this.degArr = [];
var radInc;
this.radArr = [];
var PI = Math.PI;
var radStart = (-91*PI/2);
var radEnd = (91*PI/2);
for (degInc = -8190; degInc <= 8190; degInc+=180) {
this.degArr.push(degInc);
}
for (radInc = radStart; radInc <= radEnd; radInc+=PI) {
var radIncFixed = radInc.toFixed(8);
this.radArr.push(radIncFixed);
}
}
var calc = new Calculator();
function tan(input) {
alert("tan called");
var value = Math.tan(input.value);
alert("tan called. value: " + value);
input.value = value;
}
function tanDeg(input) {
alert("tanDeg called");
var value = Math.tan(radians(input));
alert("tanDeg called. value: " + value);
input.value = value;
}
function radians(input) {
alert("radians called");
var value = input.value * Math.PI / 180;
alert("radians called. value: " + value);
return value;
}
$("#button-tan").click(function(){
alert (calc.degArr);
alert (calc.radArr);
var displayInput = $("#disp");
alert("user input: " + displayInput.val());
if (!isNaN(displayInput.val()))
{
if($("#button-mode").val() === 'DEG')
{
if (calc.radArr.indexOf(displayInput.val()) > -1)
{
alert("user input is in radArr");
}
else
{
alert("user input IS NOT in radArr");
tan(displayInput);
}
}
else
{
if (calc.degArr.indexOf(displayInput.val()) > -1)
{
alert("user input is in degArr");
}
else {
alert("user input IS NOT in degArr");
tan(displayInput);
}
}
}
else
alert("Not a number in input");
});
});
If you wanna do some tests, I created a JSFiddle demo here. Type -8190 in the first input, then click the button. It's gonna be inside the array. Then try typing "DEG" in the second input and clicking again, you'll notice code will check against another array (due to IFs). I couldn't make your auxiliar functions to calculate a value, but I think this helps you with your initial problem.
indexOf should work...
$("#button-tan").click(function(){
if (checkNum(this.form.display.value)) {
if($("#button-mode").val() === 'DEG'){
if (radArr.indexOf(Number(this.form)) > -1) {
$('#disp').val('Undefined');
} else {
tan(this.form);
}
}
else{
if (degArr.indexOf(Number(this.form)) > -1) {
$('#disp').val('Undefined');
} else {
tanDeg(this.form);
}
}
}
});

Access Control String (ACS) Parser/Interpreter with PEG.js

Preface
I'm working on creating a Access Control String (or System) (ACS) string Parser/Interpreter with PEG.js. ACS strings are commonly used on Bulletin Board Systems (BBSs) to check access rights to particular areas of the board. For example, see Renegade's ACS documentation.
Example ACS Strings
Below are some simplified strings and their English translations for illustration:
// Has GM123 OR NOT GM456
GM123|!GM456
// Has GM123 OR NOT (GM456 AND GM789) (note: AND is implied in this grammar if not specified)
GM123|!(GM456GM789)
// Has GM123 AND NOT GM456 OR has GM789
GM123!GM456|GM789
// Has GM1 OR (NOT GM2 OR GM3)
GM1|(!GM2|GM3)
What I'm Trying to Achieve
What I would like to do here is parse and interpret (or "run") the ACS string and ultimately end up with a final boolean.
Grammar So Far
Below is the PEG.js grammer I've some up with so far. Note that the ACS strings themselves are a bit more complex than the examples above (I allow for example GM['abc','def']) but I think up to this point it's fairly self explanatory.
{
function checkAccessSingle(acsName, arg) {
return true;
}
function checkAccessMulti(acsName, args, anyMatch) {
return true;
}
function makeNot(not, x) {
return not ? !x : x;
}
}
start
= acsString
whitespaceChar
= ' '
ws
= whitespaceChar*
lineTerminatorChar
= [\r\n\u2028\u2029]
decimalDigit
= [0-9]
integer
= decimalDigit+ { return parseInt(text(), 10); }
asciiPrintableChar
= [ -~]
singleAsciiStringChar
= !("'") asciiPrintableChar { return text(); }
doubleAsciiStringChar
= !('"') asciiPrintableChar { return text(); }
nonEmptyStringLiteral
= "'" chars:singleAsciiStringChar+ "'" { return chars.join(''); }
/ '"' chars:doubleAsciiStringChar+ '"' { return chars.join(''); }
AND
= '&'
OR
= '|'
NOT
= '!'
acsName
= n:([A-Z][A-Z]) { return n.join(''); }
acsArg
= nonEmptyStringLiteral
/ integer
acsArgs
= first:acsArg rest:(ws ',' ws a:acsArg { return a; })* {
var args = [ first ];
for(var i = 0; i < rest.length; ++i) {
args.push(rest[i]);
}
return args;
}
singleAcsCheck
= not:NOT? n:acsName a:acsArg* {
return function() {
makeNot(not, checkAccessSingle(n, a));
}
}
/ not:NOT? n:acsName '[' a:acsArgs ']' {
return function() {
return makeNot(not, checkAccessMulti(n, a, false));
}
}
/ not:NOT? n:acsName '{' a:acsArgs '}' {
return function() {
return makeNot(not, checkAccessMulti(n, a, true));
}
}
multiAcsCheck
= singleAcsCheck+
acsString = multiAcsCheck
Where I Need Help
The main issue I'm having (if not others I haven't run into yet!) is handling precedence with () and the OR clauses. This may be something simple, but I've worked on this for days and have some up short. Again, what I'm ultimately attempting to achieve here is to feed in an ACS string and output a final boolean result. The various ACS "commands" (e.g. 'GM' in the above example) should make method calls that do the dirty work.
Here's a quick demo that parses your example input properly and shows how you could go about evaluating the expressions on the fly (which will return a boolean):
{
function check(name, value) {
// Dummy implementation: returns true when the name starts with 'A'
return name.charAt(0) == 'A';
}
}
start
= expr
expr
= or_expr
or_expr
= left:and_expr '|' right:expr { return left || right; }
/ and_expr
and_expr
= left:not_expr '&'? right:expr { return left && right; }
/ not_expr
not_expr
= '!' value:atom { return !value; }
/ atom
atom
= acs_check
/ '(' value:expr ')' { return value; }
acs_check
= n:name a:arg { return check(n, a); }
name
= c:([A-Z][A-Z]) { return c.join(''); }
arg
= c:[A-Z]+ { return c.join(''); }
/ d:[0-9]+ { return d.join(''); }

Unexpected Identifier while selecting elements from array

I'm tearing my hair out about a Syntax Error: Unexpected Identifier that I can't figure out. I know what the error means, but as far as I can tell there's nothing wrong.
I've posted the entirety of the script I'm using; what the code is meant to do is allow a user to step through a replay of a gomoku-like game one move at a time. The game data is stored in a csv file that has a row for every move and contains multiple games. Games are identified by an index value.
var replayArray = [],
rawData=[[]];
function importData(matchID,gI) {
var dataPromise = $.ajax({
url:"./data/" + matchID + ".csv",
dataType: 'text'
})
dataPromise.then(function(data) {
rawData = data;
rawData = String(rawData);
rawData = rawData.split(/\n/);
for (h = 0; h < rawData.length; h++){
rawData[h] = String(rawData[h]).split(",");
}
}).done(function(data){
dataToArray(gI,actionReplayKeydown);
})
}
function dataToArray(gI,cb) {
var f = 0;
var g = 0;
for (var i = 0; i < rawData.length; i++) {
var turnArray = [];
if (parseInt(eval(rawData[i][1])) === gI) {
turnArray[0] = colorToNumber(eval(rawData[i][5]));
turnArray[1] = parseInt(eval(rawData[i][6]));
replayArray[g] = turnArray;
g++;
} else {
doNothing();
}
}
cb(replayArray);
}
The dataToArray function is where the problem occurs, in the line
if (parseInt(eval(rawData[i][1])) === gI) {
I think dev tools has been indicating the problem occurs at rawData[i][1], but rawData is a two dimensional array and the indexing should work fine (the first column of rawData contains the game index, and I want all rows where the value of the game index equals the index of the queried game).
The rest of the code follows but is not afaik problematic.
function colorToNumber(inputColor) {
if (inputColor === "B" ) {
return 0
} else {
return 1
}
}
function actionReplay(inputArray) {
addStone(parseInt(inputArray[f][1]),parseInt(inputArray[f][0]));
f++;
$('#whiteLastMove').remove();
$('#blackLastMove').remove();
if ((f+1)===inputArray.length){
$(document).off('keyup').on('keyup',function(e){
if (e.keyCode === 32) {
clearBoard();
createTiles(M,N);
replayArray = [];
rawData="";
}
});
}
}
function actionReplayKeydown() {
$(document).off('keyup').on('keyup',function(e) {
if (e.keyCode === 13) {
actionReplay(replayArray);
evaluateWin(0);
evaluateWin(1);
} else if (e.keyCode === 32) {
clearBoard();
createTiles(M,N);
replayArray = [];
rawData="";
} else {
doNothing();
}
});
}
function playReplay(matchID,gI) {
openCurtain(doNothing);
importData(matchID,gI);
}
I'm sure I'm missing something obvious, but I'm just not figuring it out on my own.
The issue is that there is a js syntax error in the value of rawData[i][1]. If you use your debugger you can see the value and check whether it's valid js for eval to execute.

how to get specific last decimal float value

var fNum = parseFloat("32.23.45"); results in 32.23 but I need the string from last decimal point: 23.45
For example, the following strings should return the following values:
"12.234.43.234" -> 43.234,
"345.234.32.34" -> 32.34 and
"234.34.34.234w" -> 34.34
A fairly direct solution:
function toFloat(s) {
return parseFloat(s.match(/\d+(\.|$)/g).slice(-2).join('.'));
}
For example:
toFloat("32.23.45") // 23.45
toFloat("12.234.43.234") // 43.234
toFloat("345.234.32.34") // 32.34
toFloat("234.34.34.234w") // 34.34
Update: Here's an alternative version which will more effectively handle strings with non-digits mixed in.
function toFloat(s) {
return parseFloat(s.match(/.*(\.|^)(\d+\.\d+)(\.|$)/)[2]);
}
The following will do exactly what you would like (I'm presuming that the last one should return 34.234, not 34.24).
alert (convText("12.234.43.234"));
alert (convText("345.234.32.34"));
alert (convText("234.34.34.234w"));
function convText(text) {
var offset = text.length - 1;
var finished = false;
var result = '';
var nbrDecimals = 0;
while(!finished && offset > -1) {
if(!isNaN(text[offset]) || text[offset] === '.') {
if(text[offset] === '.') {
nbrDecimals++;
}
if(nbrDecimals > 1) {
finished = true;
} else {
result = text[offset] + result;
}
}
offset--;
}
return result;
}

JavaScript array - unexpected token

Hello I'm trying to create an array of errors, and display them at once. Something like this.
if (!first_name) {
var error[] = "Заполните Фамилию";
$('#first_name').addClass('error');
} else {
$('#first_name').removeClass('error');
}
if (!second_name) {
var error[] = 'Заполните Имя';
$('#second_name').addClass('error');
} else {
$('#second_name').removeClass('error');
}
if (!last_name) {
var error[] = 'Заполните Отчество';
$('#last_name').addClass('error');
} else {
$('#last_name').removeClass('error');
}
if (!course) {
var error[] = 'Заполните Курс';
$('#course').addClass('error');
} else {
$('#course').removeClass('error');
}
if (!math && !programming && !english && !history) {
var error[] = 'Заполните хотябы один предмет';
$('#math,#programming,#english,#history').addClass('error');
} else {
$('#math,#programming,#english,#history').removeClass('error');
}
and then
if(error.length > 0) {
$(".errors").html(error);
}
But i'm getting an error Uncaught SyntaxError: Unexpected token ]
What am i doing wrong?
Two main problems - the error array was being repeatedly and incorrectly declared, and the display of the resulting array was being handled incorrectly. Here's a fix for both problems....
var error = []; // initialise empty array
if (!first_name) {
error.push( "Заполните Фамилию");
$('#first_name').addClass('error');
} else {
$('#first_name').removeClass('error');
}
if (!second_name) {
error.push( 'Заполните Имя');
$('#second_name').addClass('error');
} else {
$('#second_name').removeClass('error');
}
if (!last_name) {
error.push('Заполните Отчество');
$('#last_name').addClass('error');
} else {
$('#last_name').removeClass('error');
}
if (!course) {
error.push( 'Заполните Курс');
$('#course').addClass('error');
} else {
$('#course').removeClass('error');
}
if (!math && !programming && !english && !history) {
error.push( 'Заполните хотябы один предмет');
$('#math,#programming,#english,#history').addClass('error');
} else {
$('#math,#programming,#english,#history').removeClass('error');
}
// you will need to join the elements together somehow before displaying them
if (error.length > 0) {
var data = error.join( '<br />');
$(".errors").html(data);
}
You might also want to look at using the toggleClass function instead of add/remove, but that's up to you
All of these lines contain syntax errors:
var error[] = ...
because error[] is not a valid JavaScript identifier. Remove the []s. The closest valid variable name would be error instead of error[].
This kind of error is made painfully evident when you run your code through a JavaScript linter tool.
You are confusing JavaScript with PHP.
This is incorrect way to declare an array:
var error[] = 'Заполните Отчество';
rather:
var error = new Array();
or
var error = [];
To append values into an array using javascript :
var error = [];
error.push('Error 1');
error.push('Error 2');
Then, to display them :
$('.errors').html(
error.join('<br/>') // "Error 1<br/>Error 2"
);
Doc : push, join.
You can display all error message at once like that
var error=''
if (!first_name) {
error += "Заполните Фамилию.<br />";
$('#first_name').addClass('error');
} else {
$('#first_name').removeClass('error');
}
if (!second_name) {
error += 'Заполните Имя<br />';
$('#second_name').addClass('error');
} else {
$('#second_name').removeClass('error');
}
if (!last_name) {
error += 'Заполните Отчество<br />';
$('#last_name').addClass('error');
} else {
$('#last_name').removeClass('error');
}
if (!course) {
error += 'Заполните Курс<br />';
$('#course').addClass('error');
} else {
$('#course').removeClass('error');
}
if (!math && !programming && !english && !history) {
error +='Заполните хотябы один предмет<br />';
$('#math,#programming,#english,#history').addClass('error');
} else {
$('#math,#programming,#english,#history').removeClass('error');
}
if (error != '') {
$(".errors").html(error);
return false;
}
error is a one variable where i stored all the error and display at once on the screen.

Categories