javascript format issues with () - javascript

i got a little code but it doesnt work. i think i have an error with the ( ) cause there are too many x)
code:
if (structure == null) {
console.log('so far so good: ');
if (_.sum(Game.getObjectById(57 f5db55fc5a39220c785df5).store) < Game.getObjectById(57 f5db55fc5a39220c785df5).storeCapacity) {
if (creep.transfer(Game.getObjectById(57 f5db55fc5a39220c785df5), RESOURCE_ENERGY, creep.energy) == ERR_NOT_IN_RANGE) {
// move towards it
creep.moveTo(Game.getObjectById(57 f5db55fc5a39220c785df5));
}
}
}
anyone can understand what went wrong here? :p

You need to quote your IDs (example: 57f5db55fc5a39220c785df5 -> '57f5db55fc5a39220c785df5').
Since you're not enclosing them with quotes, it's regarded as an non-existent variable by the interpreter. And if you got some illegal characters there, it will fail even before trying to resolve the variable.

57f5db55fc5a39220c785df5 can't be a variable name, nor can it be an integer as it contains characters - so it's a string. In javascript, you need to enclose strings with " or '
if (structure == null) {
console.log('so far so good: ');
if (_.sum(Game.getObjectById("57f5db55fc5a39220c785df5").store) < Game.getObjectById("57f5db55fc5a39220c785df5").storeCapacity){
if (creep.transfer(Game.getObjectById("57f5db55fc5a39220c785df5"), RESOURCE_ENERGY, creep.energy) == ERR_NOT_IN_RANGE) {
// move towards it
creep.moveTo(Game.getObjectById("57f5db55fc5a39220c785df5"));
}
}
}

Related

Convert a string to all-lowercase-words-joined-by-dashes

function spinalCase(str) {
for ( var i = 0; i < str.length; i++) {
if ( i == 0 && /[A-Z]/.test(str[i]) ) {
str.replace(str[i], str[i].toLowerCase()) }
else if ( i !== 0 && /[A-Z]/.test(str[i])) {
str.replace(str[i], " " + str[i].toLowerCase()); } }
return str.replace(/\s+/ig, "-");
}
I have passed this test actually, but I still don't understand what did I miss here. Can somebody help me?
Many thanks
For why the code "passed this test actually" I have no answer - the test code must be defective.
What has been missed is that the string.replace method returns a new string with a replacement made if a match for the first argument string was found, or an unmodified copy of the original string if no match was found. The string on which replace is called remains unchanged.
So, while the str.replace() calls may replace characters, the updated string returned by the call is not captured.
STOP!! Why not creating it with simple array methodes? I created it with javascript streams which is worth to learn. You can check all functions here. I also added a few comments to help you understanding it:
function spinalCase(str) {
return str.split(" ") //splits the string into pieces at spaces
.map(c => c.toLowerCase()) //makes each piece lowercase
.join("-"); //combines each piece with a "-"
}
console.log(spinalCase("This Is Spinal Tap"));
console.log(spinalCase("Okay nice"));
console.log(spinalCase("Super amazing streams!"));
If you have more questions just ask below in the comments.

JS str replace Unicode aware

I am sure there is probably a dupe of this here somewhere, but if so I cannot seem to find it, nor can I glue the pieces together correctly from what I could find to get what I need. I am using JavaScript and need the following:
1) Replace the first character of a string with it's Unicode aware capitalization UNLESS the next (second) character is a - OR ` or ' (minus/dash, caret, or single-quote).
I have come close with what I could find except for getting the caret and single quote included (assuming they need to be escaped somehow) and what I believe to be a scope issue with the following because first returns undefined. I am also not positive which JS/String functions are Unicode aware:
autoCorrect = (str) => {
return str.replace(/^./, function(first) {
// if next char is not - OR ` OR ' <- not sure how to handle caret and quote
if(str.charAt(1) != '-' ) {
return first.toUpperCase(); // first is undefined here - scope??
}
});
}
Any help is appreciated!
Internally, JavaScript uses UCS-2, not UTF-8.
Handling Unicode in JavaScript isn't particularly beautiful, but possible. It becomes particularly ugly with surrogate pairs such as "🐱", but the for..of loop can handle that. Do never try to use indices on Unicode strings, as you might get only one half of a surrogate pair (which breaks Unicode).
This should handle Unicode well and do what you want:
function autoCorrect(string) {
let i = 0, firstSymbol;
const blacklist = ["-", "`", "'"];
for (const symbol of string) {
if (i === 0) {
firstSymbol = symbol;
}
else if (i === 1 && blacklist.some(char => char === symbol)) {
return string;
}
else {
const rest = string.substring(firstSymbol.length);
return firstSymbol.toUpperCase() + rest;
}
++i;
}
return string.toUpperCase();
}
Tests
console.assert(autoCorrect("δα") === "Δα");
console.assert(autoCorrect("🐱") === "🐱");
console.assert(autoCorrect("d") === "D");
console.assert(autoCorrect("t-minus-one") === "t-minus-one");
console.assert(autoCorrect("t`minus`one") === "t`minus`one");
console.assert(autoCorrect("t'minus'one") === "t'minus'one");
console.assert(autoCorrect("t^minus^one") === "T^minus^one");
console.assert(autoCorrect("t_minus_one") === "T_minus_one");

Check for multiple hash substrings

I'm trying to check for two different hash substrings and execute different code depending. This is what I have right now:
Javascript
if(window.location.hash.substring(confirm) {
$('.confirm').click();
}
elseif(window.location.hash.substring(thanks) {
$('.thanks').click();
}
Any idea what I am doing wrong?
Use indexOf with quotes to denote the string you want to search:
if(window.location.hash.indexOf('confirm') >= 0) {
$('.confirm').click();
}
else if(window.location.hash.indexOf('thanks') >= 0) {
$('.thanks').click();
}
BTW, in your original implementation, you were also missing ) in the if condition.

Declare variable in js

I have a problem using quotation marks in js...
I have an input field using this js-function
function validate(xyz) {
"+umum+" == "yeah_it_is_ok";
if(xyz == ""+umum+"") {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
What do I have to insert in the input-field to get the Hoera message?$
In other words, what is the function of a " or a + in js?
You don't have a syntax error in the function declaration,
but it will fail at execution time, because umum is not defined;
and surely you have a semantic error, because the only way to get "Hoera"
is to declare the umum var first and call the validate function later:
var umum;
validate("test value");
Of course, it always give a "too bad!" message unless you pass ""+undefined+""
as parameter. I think the right function should be:
function validate(xyz) {
var umum = "yeah_it_is_ok"; // or whatever you want to validate with..
if(xyz == umum) {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
In this case, when calling validate("yeah_it_is_ok") you'll get an "Hoera!".
You would want to declare a variable like this:
var umum = "yeah_it_is_ok";
Note the var keyword and the use of a single equals for assignment.
Also, a pair of " characters is used to enclose a string variable, and the + will concatenate two strings. However, if you wish to have a double-quotation within a string you need to escape it with a backspace \. For example:
if(xyz == "\"+umum+\"") {
Single- and double-quote characters are used to delimit string constants. The + character is an operator that serves several purposes, including string concatenation, numeric addition, and asserting numeric "positiveness" (used often for its implicit side effects).
I think you mean to write your function like this.
function validate(xyz) {
umum = "yeah_it_is_ok";
if(xyz == umum) {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
So then to answer your question, you can put the string that your looking for into the input-field. Which, since you don't have an input field in your example, we can just call the function with the correct string.
validate("yeah_it_is_ok");
Also it seems like you were thinking that you can use " or + in a variable. You can't do that. As others have suggested, you should learn the basics of JavaScript. w3schools.com and the Mozilla Developer Network are good places to do that.
http://www.w3schools.com/js/default.asp
https://developer.mozilla.org/en-US/learn/javascript
I believe you put a \ infront of it
so like
if(xyz == "\"+umum+\"") {

How do I fix this syntax error?

The code is:
function roundAmount(theDecimal) {
var s = "" + Math.round(theDecimal * 100) / 100
var i = s.indexOf('.')
if (i < 0) {
return s + ".00"
}
var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
if (i + 2 == s.length)
t += "0"
return t
}
The line with the error:
if (i < 0) return s + ".00"
The error is:
error: expected (;)
does anyone know how to fix this?
About your script:
The problem in the script above is that last if statement which does some operations followed by a return. You need a semi-colon after the operation.
In the future, as good practice, make sure to put a semi-colon after every valid statement. That way this won't bother you.
Think of each line as a thought, and curly braces as ways to "group" and "relate" thoughts together.
The below is a full thought that says "give me a variable "i" and give it the value 1 + 2;
var i = 1 + 2;
The below is a full thought about a condition that says "If i is 3 then add 1 to i". The thought "add 1 to i" is its own thought, so it needs a semicolon. Since the curlybraces for the IF statement are special in that they don't need a semi-colon after their "full thought" as long as you put a "block" (which is what curlybraces really make) after it, to enclose the thought.
This means the following is valid:
if( i == 3 ) {
i = i + 1;
}
The following is not valid because the semi-colon after the if ends the "thought" before the if knows what to do if i equals 3:
if( i == 3 ) ; {
i = i + 1;
}
For a basic JavaScript tutorial, check out W3Schools.
"There must be a better way?"
Any time you find yourself doing a lot of string operations on decmials, it's a good idea to ask yourself "is there a better way to do this?".
It looks like you're writing a function to round a number to the nearest hundredths while displaying two decimal points. There's a much easier way to do this. You can just round to the nearest hundredths and have javascript output the fixed point number.
Example:
function roundAmount( theDecimal ) {
//first round to the nearest hundredth
//then return the value with two decimal places as a string
return theDecimal.toFixed( 2 );
}
if (i < 0) return s + ".00";
Note the ; at the end of the statement. Personally, I prefer surrounding almost all my ifs in {} such as
if (i < 0)
{
return s + ".00";
}
Which helps in debugging and stepping though code.
It's expecting a semicolon, so add a semicolon.
if (i < 0)
return s + ".00";
Add a semicolon at the end of the line! Like this:
if (i < 0) return s + ".00";
I don't see anything particularly wrong with the code you posted in the earlier comments, but may I suggest always adding a semi-colon to the end of your statements. Though they are not required, it usually makes it easier to debug problems such as these.

Categories

Resources