there's something that i just solved but I don't understand why i got that kind of behavior, here's my js code
function fibonacci () {
let fibonacciNumber = document.getElementById("my-input").value;
let numberInitialize = 0;
let numberNext = 1;
let sum = numberInitialize + numberNext;
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
for (index = 1; index < fibonacciNumber; index++)
{
numberInitialize = numberNext;
numberNext = sum;
sum = numberInitialize + numberNext;
console.log(sum);
console.log("premier tour");
}
console.log(sum);
document.getElementById("fibo-result").innerHTML = `${sum}`;
}
So on the html side I just have an input and im writing down number, my questions concerned this line of code
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
when im writing down 0, its still printing one but i write the condition like that
if (fibonacciNumber === "" || fibonacciNumber <= 0) {
return (0);
}
its working and when I got 0 as an input nothing is printed like i wanted, my question is: Why when im putting fibonacciNumber === 0 return (0) its not working properly its 0, the condition match no ?
Thanks guys
The reason is because your field actually has the string "0". The identity operator (===) will not do any type coercion before comparing the values, so "0" === 0 is false.
Numeric comparison operators like <= will do type coercion, so "0" <= 0 will evaluate to true.
You can see this all in action below.
console.log("0" === 0);
console.log("0" <= 0);
You will need to use parseInt() and then treat the input as integer.
let fibonacciNumber = parseInt(document.getElementById("my-input").value);
Related
I was only allowed to use google document for writing.
Could you please tell me what I did wrong? The recruiter wont get back to me when I asked her why I failed
Task 1:
Implement function verify(text) which verifies whether parentheses within text are
correctly nested. You need to consider three kinds: (), [], <> and only these kinds.
My Answer:
const verify = (text) => {
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
}
};
return parenthesesStack.length ? 0 : 1;
}
Task 2:
Simplify the implementation below as much as you can.
Even better if you can also improve performance as part of the simplification!
FYI: This code is over 35 lines and over 300 tokens, but it can be written in
5 lines and in less than 60 tokens.
Function on the next page.
// ‘a’ and ‘b’ are single character strings
function func2(s, a, b) {
var match_empty=/^$/ ;
if (s.match(match_empty)) {
return -1;
}
var i=s.length-1;
var aIndex=-1;
var bIndex=-1;
while ((aIndex==-1) && (bIndex==-1) && (i>=0)) {
if (s.substring(i, i+1) == a)
aIndex=i;
if (s.substring(i, i+1) == b)
bIndex=i;
i--;
}
if (aIndex != -1) {
if (bIndex == -1)
return aIndex;
return Math.max(aIndex, bIndex);
} else {
if (bIndex != -1)
return bIndex;
return -1;
}
};
My Answer:
const funcSimplified = (s,a,b) => {
if(s.match(/^$/)) {
return -1;
} else {
return Math.max(s.indexOf(a),s.indexOf(b))
}
}
For starters, I'd be clear about exactly what the recruiter asked. Bold and bullet point it and be explicit.
Secondly, I would have failed you from your first 'for' statement.
See my notes:
// Bonus - add jsdoc description, example, expected variables for added intention.
const verify = (text) => {
// verify what? be specific.
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
// this could have been a map method or reduce method depending on what you were getting out of it. Rarely is a for loop like this used now unless you need to break out of it for performance reasons.
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
// parenthesesStack.length - 1 === -1.
// parenthesesStack[-1] = undefined
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
// “ will break. Use "
// would have been more performant and maintainable to create a variable like this:
// const textOutput = text[i]
// if (textOutput === "(" || textOutput === "[" || textOutput === "<") {
parenthesisStack.push(textOutput)
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
// There is nothing in parenthesisStack to pop
}
};
return parenthesesStack.length ? 0 : 1;
// Will always be 0.
}
Not exactly what the intention of your function or logic is doing, but It would fail based on what I can see.
Test it in a browser or use typescript playground. You can write javascript in there too.
Hard to tell without the recruiter feedback. But i can tell that you missundertood the second function.
func2("mystrs", 's', 'm') // returns 5
funcSimplified("mystrs", 's', 'm') // returns 3
You are returning Math.max(s.indexOf(a),s.indexOf(b)) instead of Math.max(s.lastIndexOf(a), s.lastIndexOf(b))
The original code start at i=len(str) - 1 and decrease up to 0. They are reading the string backward.
A possible implementation could have been
const lastOccurenceOf = (s,a,b) => {
// Check for falsyness (undefined, null, or empty string)
if (!s) return -1;
// ensure -1 value if search term is empty
const lastIndexOfA = a ? s.lastIndexOf(a) : -1
const lastIndexOfB = b ? s.lastIndexOf(b) : -1
return Math.max(lastIndexOfA, lastIndexOfB)
}
or a more concise example, which is arguably worse (because less readable)
const lastOccurenceOf = (s,a,b) => {
const safeStr = s || '';
return Math.max(safeStr.lastIndexOf(a || undefined), safeStr.lastIndexOf(b || undefined))
}
I'm using a || undefined to force a to be undefined if it is an empty string, because:
"canal".lastIndexOf("") = 5
"canal".lastIndexOf(undefined) = -1
original function would have returned -1 if case of an empty a or b
Also, have you ask if you were allowed to use ES6+ syntax ? You've been given a vanilla JS and you implemented the equivalent using ES6+. Some recruiters have vicious POV.
I'm looking at this code:
for (let n = 1; n <=100; n++) {
let output = "";
if (n % 3 == 0) output += "Fizz";
if (n % 5 == 0) output += "Buzz";
console.log(output || n);
}
How the console decides when to print the numbers or the words?
"" is a falsy value, so when performing "" || 1, it will be read as false || 1, which will print 1.
You can read more at https://developer.mozilla.org/en-US/docs/Glossary/Falsy
The logical OR operator works because in Javascript, it returns the first expression if if truthy, otherwise it returns the second expression.
Read more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical
function containsPunctuation(word)
{
var punctuation = [";", "!", ".", "?", ",", "-"];
for(var i = 0; i < punctuation.length; i++)
{
if(word.indexOf(punctuation[i]) !== -1)
{
return true;
}
}
return false;
}
function isStopWord(word, stopWords)
{
for (var i = 0; i < stopWords.length; i += 1)
{
var stopWord = stopWords[i];
if ((containsPunctuation(word)) && (word.indexOf(stopWord) === 0) && (word.length === stopWord.length + 1))
{
return true;
}
else if (word === stopWord)
{
return true;
}
}
return false;
}
At the blockquote, how is containsPunctuation(word) && (word.indexOf(stopWord) === 0? Can someone explain why they are both equal to zero?
I'm also not sure why (word.length === stopWord.length + 1) is used.
I think you are reading the if statement a little bit incorrectly. Not knowing what the isStopWord function is supposed to do I can't tell you what the (word.length === stopWord.length + 1) part is all about.
I can tell you that (containsPunctuation(word)) is its own boolean value, because that function returns a true or false. That part is its own evaluation.
The second part (word.indexOf(stopWord) === 0) is also a complete evaluation. That part has nothing to do with the containsPunctuation function. The indexOf function returns an integer, so it can equal 0.
The third part (word.length === stopWord.length + 1) is checking to see if the length of word is one more than the length of stopWord.
They are all separate evaluations and because you are using && between them all, they all must evaluate as true in order for the code block that follows it to run.
Here are the indexOf docs for string and array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
--EDIT--
in light of your comment, my guess for the (word.length === stopWord.length + 1) is because the word might contain a punctuation mark that is not included in the stopWord so this if check will only return true if the punctuation is at the end of the word because the indexOf check will only return 0 if the stopword starts at the beginning of the word.
I'm writing a primality checker in in j/s and I was wondering why I'm getting true as a return for when I test 55... It seems to work fine for all the other cases I checked just not 55, can someone tell me where I went wrong?
var isPrime = function(num){
if (num === 2){
return true;
}
else if(num%2 === 0){
return false;
}
else{
var i = 2;
while(i<num){
if((num/i) % i === 0 ){
return false;
}
i++
}
return true;
}
};
Thanks in advance and apologies for the noobness!
if((num/i) % i === 0 ){
return false;
}
What is this case?
Shouldn't it be
if(num % i === 0 ){
return false;
}
Just as #Andrey pointed out, your if statement inside the while loop is not correct. For 55 at i=5 you should get false for 55 being prime, but 55/5 % 5 == 1 Also you could use just == instead of === for logical equals, since === checks if both values and type are equal, which is not necessary here.
Try this.
var isPrime = function isPrime(value) {
var i = 2;
for(i; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
};
Even if your bug may be solved, I'd recommend to think about some other aspects to optimize your code:
Clarify your corner cases: In the beginning, check for n<2 -> return false. At least to math theory primes are defined as natural number larger then 1, so 1 is by definition not a prime like all the negative numbers. Your code won't handle negative numbers correctly.
You don't have to check all divisors up to n-1. You can obviously stop checking at n/2, but there are even proofs for tighter bounds which means you can stop checking already at √n if I'm right. To further optimize, you don't have to check even divisors >2.
else {
var i = 3;
while ( i < num/2 ) {
if( num % i == 0 ) {
return false;
}
i+=2;
}
return true;
}
See https://en.wikipedia.org/wiki/Primality_test for details about testing of primes.
P.S: I just wrote the code here in the text box, but it looks like it might work.
In javascript, how can you check if a string is a natural number (including zeros)?
Thanks
Examples:
'0' // ok
'1' // ok
'-1' // not ok
'-1.1' // not ok
'1.1' // not ok
'abc' // not ok
Here is my solution:
function isNaturalNumber(n) {
n = n.toString(); // force the value incase it is not
var n1 = Math.abs(n),
n2 = parseInt(n, 10);
return !isNaN(n1) && n2 === n1 && n1.toString() === n;
}
Here is the demo:
var tests = [
'0',
'1',
'-1',
'-1.1',
'1.1',
'12abc123',
'+42',
'0xFF',
'5e3'
];
function isNaturalNumber(n) {
n = n.toString(); // force the value incase it is not
var n1 = Math.abs(n),
n2 = parseInt(n, 10);
return !isNaN(n1) && n2 === n1 && n1.toString() === n;
}
console.log(tests.map(isNaturalNumber));
here is the output:
[true, true, false, false, false, false, false, false, false]
DEMO: http://jsfiddle.net/rlemon/zN6j3/1
Note: this is not a true natural number, however I understood it that the OP did not want a real natural number. Here is the solution for real natural numbers:
function nat(n) {
return n >= 0 && Math.floor(n) === +n;
}
http://jsfiddle.net/KJcKJ/
provided by #BenjaminGruenbaum
Use a regular expression
function isNaturalNumber (str) {
var pattern = /^(0|([1-9]\d*))$/;
return pattern.test(str);
}
The function will return either true or false so you can do a check based on that.
if(isNaturalNumber(number)){
// Do something if the number is natural
}else{
// Do something if it's not natural
}
Source: http://www.codingforums.com/showthread.php?t=148668
If you have a regex phobia, you could do something like this:
function is_natural(s) {
var n = parseInt(s, 10);
return n >= 0 && n.toString() === s;
}
And some tests:
> is_natural('2')
true
> is_natural('2x')
false
> is_natural('2.0')
false
> is_natural('NaN')
false
> is_natural('0')
true
> is_natural(' 2')
false
You can do if(num.match(/^\d+$/)){ alert(num) }
You could use
var inN = !!(+v === Math.abs(~~v) && v.length);
The last test ensures '' gives false.
Note that it wouldn't work with very big numbers (like 1e14)
You can check for int with regexp:
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('Natural');
}
function isNatural(num){
var intNum = parseInt(num);
var floatNum = parseFloat(num);
return (intNum == floatNum) && intNum >=0;
}
Number() parses string input accurately. ("12basdf" is NaN, "+42" is 42, etc.). Use that to check and see if it's a number at all. From there, just do a couple checks to make sure that the input meets the rest of your criteria.
function isNatural(n) {
if(/\./.test(n)) return false; //delete this line if you want n.0 to be true
var num = Number(n);
if(!num && num !== 0) return false;
if(num < 0) return false;
if(num != parseInt(num)) return false; //checks for any decimal digits
return true;
}
function isNatural(n){
return Math.abs(parseInt(+n)) -n === 0;
}
This returns false for '1 dog', '-1', '' or '1.1', and returns true
for non-negative integers or their strings, including '1.2345e12',
and not '1.2345e3'.
I know this thread is a bit old but I believe I've found the most accurate solution thus far:
function isNat(n) { // A natural number is...
return n != null // ...a defined value,
&& n >= 0 // ...nonnegative,
&& n != Infinity // ...finite,
&& typeof n !== 'boolean' // ...not a boolean,
&& !(n instanceof Array) // ...not an array,
&& !(n instanceof Date) // ...not a date,
&& Math.floor(n) === +n; // ...and whole.
}
My solution is basically an evolution of the contribution made by #BenjaminGruenbaum.
To back up my claim of accuracy I've greatly expanded upon the tests that #rlemon made and put every proposed solution including my own through them:
http://jsfiddle.net/icylace/qY3FS/1/
As expected some solutions are more accurate than others but mine is the only one that passes all the tests.
EDIT: I updated isNat() to rely less on duck typing and thus should be even more reliable.
This is how I check if a string is a natural number (including zeros!).
var str = '0' // ok
var str1 = '1' // ok
var str2 = '-1' // not ok
var str3 = '-1.1' // not ok
var str4 = '1.1' // not ok
var str5 = 'abc' // not ok
console.log("is str natural number (including zeros): ", Number.isInteger(Number(str)) && Number(str) >= 0)
console.log("is str1 natural number (including zeros): ", Number.isInteger(Number(str1)) && Number(str1) >= 0)
console.log("is str2 natural number (including zeros): ", Number.isInteger(Number(str2)) && Number(str2) >= 0)
console.log("is str3 natural number (including zeros): ", Number.isInteger(Number(str3)) && Number(str3) >= 0)
console.log("is str4 natural number (including zeros): ", Number.isInteger(Number(str4)) && Number(str4) >= 0)
console.log("is str5 natural number (including zeros): ", Number.isInteger(Number(str5)) && Number(str5) >= 0)
const func = (number) => {
return Math.floor(number) === number
}
Convert the string to a number and then check:
function isNatural( s ) {
var n = +s;
return !isNaN(n) && n >= 0 && n === Math.floor(n);
}
function isNatural(number){
var regex=/^\d*$/;
return regex.test( number );
}
function isNatural(n) {
return Number(n) >= 0 && Number(n) % 1 === 0;
}
Why not simply use modulo?
if(num % 1 !== 0) return false;
Use /^\d+$/ will match 000.
so use /^[1-9]\d*$|^0$/ match positive integer or 0 will be right.