I have some code that is not passing lint. Is there is a better way to do this?
The first error is
lint warning: leading zeros make an octal number
function getNumberCounter(lastNumberString, simple){
var myCount;
if(!lastNumberString){
return "-1";
}
else{
switch(lastNumberString.split("-")[1]){
case "08" : myCount = 9;
break;
case "09" : myCount = 10;
break;
case "99" : myCount = 00;
break;
default : myCount = parseInt((lastNumberString.split("-")[1]),10) + 1;
break;
}
if(!simple){
if(myCount <= 9){
return ('0' + myCount);
}
}
return myCount;
}
}
and the other one is
lint warning: increment (++) and decrement (--) operators used as part of greater statement
function getRandomString(_length){
_retString = "";
_charSet = "0123456789abcdefghijklmnopqrstuvwxyz";
while(_length--){
_retString += _charSet.charAt(Random(0, _charSet.length-1));
Delay(1);
}
return _retString;
}
also this is javascript but it is not html type does anyone know what type it is, tried to use a javascript checker and it wants me to write html based code.
why is this happening and does it have an actual impact on the software I am using on my computer.
In many languages, a number with a leading zero is considered to be a octal (i.e. base 8) literal, apart from 0 itself. For example 012 is the decimal number ten, even though it looks more like twelve. So 00 is considered to be an octal number, although it's obviously zero.
Octal literals are however a syntax error in strict mode, as octal numbers were never part of the ECMAScript standard. I imagine your linter is enforcing the same rule.
So the fix to your first problem is simple:
case "99" : myCount = 0; // Drop one of the zeroes.
The second problem is here:
while(_length--){
You are decrementing the value of length and also reading either its original or new value. Your linter is complaining because you are doing both. Doing so makes for code that is difficult to read. In particular, does the loop run length times or length - 1 times? It's not clear.
Your while loop always runs a fixed number of times, so from a stylistic point of view you would be better off with a for loop:
for (var i = 0; i < length; ++i) {
_retString += _charSet.charAt(Random(0, _charSet.length-1));
Delay(1);
}
As you're now only using ++ in the ++i statement within the for loop, this should avoid lint warnings.
Related
In the function below, the for loop sometimes skips one iteration.
In some rare cases, I've also found it skipping two iterations.
This sometimes breaks my code and would probably affect my future codes, if my understanding of the for loop remains incomplete.
I further looked into the matter and tried the same with a while loop and found out that this problem doesn't happens if a while loop is used.
Why is the for-loop sometimes skipping some iterations ?
function forLoopString(len)
{
var string = 'abcdefghijklmnopqrstuvwxyz0123456789';
var character = '',
randomString = '';
for (var i = 0; i < len; i++)
{
character = string.charAt(Math.floor(Math.random() * string.length-1) + 0);
randomString += character;
}
if(randomString.length < len)
{
console.log('Less than required length!');
randomString = randomString + '5';
}
return randomString;
}
JSFiddle
The loop shown won't "skip" any iterations, but will iterate from [0, len) as told to do.
However, a negative argument to charAt makes it seem like it "skips" because "foo".charAt(-1) == "". The same empty-string result holds for any out-of-bounds to String.charAt:
.. If the index you supply [to charAt] is out of range, JavaScript returns an empty string.
A correction that yields an always-valid index would merely be Math.floor(Math.random() * string.length), without the -1.
Although this is slightly biased (for anyone that really cares) this is 'correct' because Math.random returns a number in the range [0, 1). Thus Math.random() * len returns a value from [0, len); and as an Integer in the same interval after the floor.
Also, it would be good to choose more useful variable names.. and, as Ed points out the +0 is irrelevant because Math.floor returns a (integer) number.
The random number is sometimes negative, that's why a character is skipper from randomString in those cases.
https://jsfiddle.net/ojbp0evz/3/
Use Math.abs for example.
Your problem is HERE:
character = string.charAt(Math.floor(Math.random() * string.length-1) + 0);
if your rand is less than 0, you will get a negative number, and therefor, you won't get any character. You must encapsulate your string.length-1 like so:
character = string.charAt(Math.floor(Math.random() * (string.length-1)));
Updated fiddle: DEMO
Always remember: MULTIPLICATIONS GOES FIRST!!
EDIT: string.length is 36, you dont need to substract 1 to it, just multiply
character = string.charAt(Math.floor(Math.random() * string.length));
var x = 02345;
var y = x.toString();
alert(y);
I realized that there is a problem converting leading zeroes number to string in JavaScript using the toString() method.
As you can see from the output of the code above, the output is 1253 instead of the supposedly 02345.
If the leading zero is removed, the code will work as expected, why? What is happening with the code above so I can change it to work as expected.
var x = 2345;
var y = x.toString();
alert(y);
EDIT : The reason I asked this question is because I have two different codes that work differently despite being very similar. After reading that this question has nothing to do with the toString() method, why does the first set of code below not detect the number as an octal value but the second set of code does.
var num=window.prompt(); // num = 0012222
var str = num.toString();
var result = [str[0]];
for(var x=1; x<str.length; x++)
{
if((str[x-1]%2 === 0)&&(str[x]%2 === 0))
{
result.push('-', str[x]);
}
else
{
result.push(str[x]);
}
}
alert(result.join('')); //Outputs : 0-012-2-2-2
The other code :
function numberDash(num) {
var stringNumber = num.toString();
var output = [stringNumber[0]];
for (var i = 1; i < stringNumber.length; i++) {
if (stringNumber[i-1] % 2 === 0 && stringNumber[i] % 2 === 0) {
output.push('-', stringNumber[i]);
} else {
output.push(stringNumber[i]);
}
}
return output.join('');
}
numberDash(0012222) // Outputs : "52-6-6";
Many JavaScript engines add octal numeric literals to the specification. The leading zero indicates octal (base 8). 2345 in base 8 (octal) is 1253 in base 10 (decimal):
Octal Decimal
----- --------------------
2 2 * 8 * 8 * 8 = 1024
3 3 * 8 * 8 = 192
4 4 * 8 = 32
5 5
----- --------------------
2345 1253
You can disable that using strict mode. See §B.1.1 of the specification. Doing so makes 02345 a syntax error.
So it's nothing to do with toString, it's just that the 02345 in your code isn't the value you expect.
Re your updated question:
why does the first set of code below not detect the number as an octal value but the second set of code does
Because in the first code, you're not dealing with a number, you're dealing with a string. window.prompt returns a string, not a number, even if what you type in is all digits.
Even if you converted the string to a number via Number(num) or +num, the rules for runtime string->number conversion are different from the rules for parsing JavaScript source code.
var x = 02345;
var y = x.toString("8");
alert(y);
This will give you 2345
Leading zero is interpreted as octal value.
If you need number converted to string with leading zero, use my method but simply modify it like this var y = "0" + x.toString("8")
Hello I have some experience with javascript but I would really like to learn how to program in C and one of the ways I am trying to learn is by converting some simple javascript code into C. My current attempt at converting a simple program compiles without any errors however doesn`t produce the answer I want it to. The javscript code produces the correct answer and I wrote it to solve project euler problem number 5 which can be found here: https://projecteuler.net/problem=5
Here is the working js code:
var number = 2520;
var count = 1;
var solved = false;
while (!solved) {
if (number % count === 0) {
if (count === 20) {
solved = true;
console.log(number);
} else {
count++;
}
} else {
number++;
count = 1;
}
}
Here is the C conversion which does not work:
#include <stdio.h>
int main () {
unsigned int number = 2520;
unsigned int count = 1;
unsigned int solved = 0;
while ((solved = 0)) {
if (number % count == 0) {
if (count == 20) {
solved = 1;
printf("%number");
} else {
count++;
}
} else {
number++;
count = 1;
}
}
return 0;
}
while ((solved = 0)) {
You can use the same syntax you would use in js here, namely, while (!solved), or ==, but just = is an assignment.
printf("%number");
Doesn't mean what you think it means, which is why it's not an actual error (%n is a distinct specifier, and with no corresponding input, you'd get umber as the output). To reproduce console.log() you'd want:
printf("%d\n", (int)number);
Or
printf("%u\n", number);
Notice the explicit \n, since printf() does not add a newline otherwise.
Replace
while (solved = 0)
with
while (!solved)
and
print("%number")
with
print("%u\n",number)
I know its already answered, but you should know why.
while ((solved = 0))
Will actually set solved to 0 AND return 0 (which is interpreted as false). So the while loop is exited right away.
printf also takes a pretty strictly formatted string for the first one (just typeing what makes sense is guarenteed to be wrong). The compiler has know way to know what is inside the string is anything other than a string (C++ has (almost) NO reflection, unlike javascript: your written code dissapears into ones and zeros). printf needs to take number in as the second argument. Try printf("%i\n",number);. That says "Print an integer followed by a newline. The integer's value is number."
Welcome to C! Your biggest problem going into is is going to be my biggest problem with Java Script: C is strictly typed with no reflection, while javascript has no types with almost everything relying on some sort of reflection.
Wondering if anyone could shed some light as I’m pulling my hair out over this one!
I have written a simple function to validate a users Date of birth which is all well and good, or at least it was until I realised it wasn't working as expected!
The function, as below, takes 2 parameters, dobNum (the value of an input field) and dmy (a switch variable that receives either ‘dd’, ‘mm’ or ‘yyyy’). The function is called as follows with the value of an input field so there shouldn’t be any object based problems:
onblur=”validateDOB(this.value, ‘mm’);
I have spent ages trying to get to the bottom of this and there seems to be a problem with the parseInt() statement.
This works fine for the days and months until you pass either a 08 (zero, eight) or a 09 (zero,nine). Here the result of the parseInt() returns as 0 rather than an 8 or 9 respectively.
But this is only a problem with 08 and 09, passing numbers 01 to 07 returns 1 to 7 as expected.
Similarly, when passing single digits, 1 to 9, to the function, parseInt() returns the appropriate value as an integer.
Really struggling to fathom this one out. Conversely removing the parseInt statement completely seems to work however this leaves the dobNum value as a string which I don’t feel is particularly good practice.
Can anyone shed some light on this please? (this problem occurs in both firefox and IE)
Many thanks,
SMc
var DOBddOK = false;
var DOBmmOK = false;
var DOByyyyOK = false;
function validateDOB (dobNum, dmy) {
// Set Regexp based on dmy var.
if (dmy.length == 2) var reg = /^([0-9]{1,2})$/;
else var reg = /^([0-9]{4})$/;
var numOK = reg.test(dobNum);
alert("NumOK: "+numOK); //test
// If dobNum value passes regExp test then convert it to an integer
if (numOK) {
var numVar = parseInt(dobNum);
//var numVar = dobNum;
alert("NumVar: "+numVar); //test
}
alert("dmy: "+dmy); //test
switch (dmy) {
case "dd":
if (numOK && numVar <= 31 && numVar > 0) DOBddOK = true;
else DOBddOK = false;
break;
case "mm":
if (numOK && numVar <= 12 && numVar > 0) DOBmmOK = true;
else DOBmmOK = false;
break;
case "yyyy":
var d = new Date();
d = d.getFullYear();
if (numOK && numVar <= (d-18) && numVar >= (d-80)) DOByyyyOK = true;
else DOByyyyOK = false;
break;
}
}
When the parseInt function finds a leading zero in the passed string, it will implicitly parse the number as octal.
It is always recommended to use the radix argument:
parseInt('08', 10); // 8
parseInt('09', 10); // 9
This have caused so many problems over the time that in the new version of the language standard, ECMAScript 5, the implicit octal detection has been removed from the parseInt algorithm. But ES5 is not completely supported yet.
There are other ways to convert a String to Number in JavaScript that do not present this problem, for example:
The unary plus operator:
+'08'; // 8
The Number constructor called as a Function:
Number('08'); // 8
In my opinion parseInt and the later two ways I've described have a (subtly) different semantic meaning.
The former is clearly parsing, for example:
parseInt('12px'); // 12
parseInt('10yo'); // 10
parseInt('1111', 2); // 15
And the last two ways are for doing String to Number type conversion.
It's treating strings with a leading zero as octal, you can specify a second parameter giving the radix as 10.
See link text
Try to use the radix parseInt(dobNum, 10) to parse your integer in base 10
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.