This question already has answers here:
JavaScript switch with logical operators?
(5 answers)
Closed 2 years ago.
I'm running two seemingly identical statements to check whether a number is positive, negative or zero.
The if statement returns the expected result.
The switch statement always returns the default.
Why?
In this example I pass "2" (type: number) and I get + in the if statement and ? in the switch statement.
// Verify whether a number is positive, negative or Zero:
function myFuncIf(y) {
let result = null;
console.log("y is " + y);
console.log("y is " + typeof(y));
if (y > 0) {
return "+";
} else if (y < 0) {
return "-";
} else {
return "?";
}
}
function myFuncSwitch(y) {
let result = null;
console.log("y is " + y);
console.log("y is " + typeof(y));
switch (y) {
case (y > 0):
result = "+";
break;
case (y < 0):
result = "-";
break;
default:
result = "?";
}
return result;
}
console.log(myFuncIf(2));
console.log(myFuncSwitch(2));
switch matches the value.
The value of y is 2.
Your first case will match True.
Your second will match False.
You probably want your switch to look like this:
switch (Math.sign(y)) {
case (1):
result = "+";
break;
case (-1):
result = "-";
break;
default:
result = "?";
}
See docs here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
Related
What I'm trying to accomplish:
I'm trying to create a regex program that can do the following:
A^C + B^C = (A + B)^C
My regex:
/(^|[^^*/\dt.-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?([+-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?(?=$|[^(^*/!\d\.])/
Broken down into chunks:
/(^|[^^*/\dt.-]) characters that shouldn't precede the match
(-?)(\d+\.?(?:\d+)?)x a (negative) number followed by an x
(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))? possibly x raised to a number or something between parentheses
([+-]) plus or minus
(-?)(\d+\.?(?:\d+)?)x a (negative) number followed by an x
(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))? Same power thing
(?=$|[^(^*/!\d\.])/ characters that shouldn't follow the match
Sample text:
What it does is it finds matches like the fourth example here, where the powers, between the parentheses aren't the same. I then check in the function I provide in the replace regex method that the powers are the same, and the equation can be simplified.
5-3x+7x //Here it finds 3x+7x
3x^2+4x^2-5 //Here it finds 3x^2+4x^2
3x^2+5x^3+8x^3 //Here it finds 3x^2 + 5x^3, but not 5x^3 + 8x^3 <-- The problem
3x^(5x+7x)+5x^(6x+6x) //Here it finds 3x^(5x+7x)+5x^(6x+6x) but not the inner 5x+7x and 6x+6x <--Also the problem
What I've tried:
I tried implementing this solution, but I don't know how to use that with the regex replace function: stackoverflow: How can I match overlapping strings with regex?
My code:
Expected result: 3x^2+13x^3
Actual result: 3x^2+5x^3+8x^3 (same as input)
var solvedEquation = "3x^2+5x^3+8x^3";
addXterms();
console.log(solvedEquation);
function addXterms() {
var legitPattern = true;
var addVariablesPattern = /(^|[^^*/\dt.-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?([+-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?(?=$|[^(^*/!\d\.])/g;
while (addVariablesPattern.test(solvedEquation)) {
solvedEquation = solvedEquation.replace(addVariablesPattern, function (match, operator1, minusSign1, num1, numPower1, parPower1, operator2, minusSign2, num2, numPower2, parPower2) {
var result;
if (numPower1 == numPower2 && parPower1 == parPower2) {
num1 = parseFloat(num1) * (minusSign1 == "-" ? -1 : 1);
num2 = parseFloat(num2) * (minusSign2 == "-" ? -1 : 1);
if (operator2 == "+") {
result = num1 + num2;
} else {
result = num1 - num2;
}
equationSolved = false;
if (numPower1 != "" && typeof numPower1 != "undefined") {
return operator1 + result + "x^" + numPower1;
} else if (parPower1 != "" && typeof parPower1 != "undefined") {
return operator1 + result + "x^(" + parPower1 + ")";
} else {
return operator1 + result + "x";
}
} else {
legitPattern = false;
return match;
}
});
}
}
This is my code. I am not getting any Fizz buzz printed. I am only getting numbers. Could anyone explain why? Thanks
printOut = "";
for (var x=1; x < 101 ; x++) {
switch(x) {
case((x%3) == 0):
printOut+="\n"+ "Fizz" ;
break;
case((x%5) == 0):
printOut+="\nBuzz";
break;
default:
printOut+="\n" + x ;
break;
}
}
console.log(printOut);
check how you're using the switch statement: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
in the switch line x is your expression and ((x%5) == 0) is your value. I think what you mean to do is a handful of if/else statements.
You're using the switch statement improperly. Each case (value): is basically supposed to be run whenever x equals value.
To solve this problem, simply remove the switch statement entirely, and substitute ifs for each case:
for (var x = 1; x < 101; x++) {
if ((x % 3) == 0)
printOut += "\n" + "Fizz";
else if ((x % 5) == 0)
printOut += "\nBuzz";
else
printOut += "\n" + x;
}
You are trying to match the value of x with expressions whose values are either true or false. You can pass true in the switch and the switch will "match" with the first case statement that evaluates as true.
While this sort-a works, I would recommend just doing if/else statements. This won't work for number 30 which is both True for X%3 and x%5. It will match with the x%3 first and stop there.
printOut = "";
for (var x=1; x < 101 ; x++) {
switch(true) {
case((x%3) == 0):
printOut+="\n"+ "Fizz" ;
break;
case((x%5) == 0):
printOut+="\nBuzz";
break;
default:
printOut+="\n" + x ;
break;
}
}
console.log(printOut);
This question already has answers here:
JavaScript: Simple way to check if variable is equal to one of two or more values? [duplicate]
(8 answers)
Closed 7 years ago.
Is there a more efficient/ concise/ eloquent way to write this:
else if ((aInd === 3)||(aInd === 7)||(aInd === 9)||(aInd === 19)
letter = alphabet[aInd + 1].toUpperCase();
Is there any valid syntax that looks like
if (a === (3 || 7 || 13 || 19) {do this}
... or lets you group sets of values of for a single variable in a more concise way than a bunch of boolean expressions with || logic?
Background: Novice programmer, working through a basic cypher challenge on coderbyte that requires taking a certain action (capitalizing) if the letter is a vowel. For reasons of simplicity (because it's used elsewhere in the program) I declared an array alphabet containing each letter a-z in the form of a string. The 'cypher' also transposes every letter one to the right, so the alphabet indexes of the letters to become vowels are 3, 7, 13, and 19. aInd represents the index of letter in the alphabet.
Full code:
function letterChanges(str) {
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var words = str.toLowerCase().split(' '), senArray = words.map(function(word) {return word.split('')});
senArray.forEach(function(word) {
word = word.filter(function(letter, index, word) {
if ((Boolean(alphabet.indexOf(letter))) === false) return false;
else return true;
});
});
senArray[0].map(function(letter) {
var aInd = alphabet.indexOf(letter);
switch (aInd) {
case 25:
letter = alphabet[aInd].toUpperCase();
break;
case (3 || 7 || 13 || 19):
letter = alphabet[aInd + 1].toUpperCase();
console.log(letter);
break;
default:
letter = alphabet[aInd + 1];
break;
}
return letter;
})
return senArray.map(function(word) {
return word.map(function(letter) {
var aInd = alphabet.indexOf(letter);
if (aInd === 25) {letter = alphabet[aInd].toUpperCase();}
else if ((aInd === 3)||(aInd === 7)||(aInd === 13)||(aInd === 19)) {letter = alphabet[aInd + 1].toUpperCase();}
else {letter = alphabet[aInd + 1];}
return letter;
}).join('');
}).join(' ');
}
letterChanges("Input string goes here.");
Pass the values as an array and check the indexOf.
In your case,
if ([3, 7, 13, 19].indexOf(aInd) > -1) {
letter = alphabet[aInd + 1].toUpperCase();
}
This question already has answers here:
JavaScript conditional switch statement
(5 answers)
Closed 7 years ago.
I have a bmi calculator and converted the conditionals to a switch statement to make it a bit cleaner. However, now the code is breaking and not causing the var result to be set so it can be displayed.
Any ideas what I am missing here?
JS
$('#calculatebutton').click(function () {
var weight = parseInt($('#weight-lb').val()),
heightInches = parseInt($('#height-ft').val()) + parseInt($('#height-in').val()),
heightsqaured = (heightInches) * (heightInches),
result = ((weight) / (heightsqaured) * 703);
switch(result) {
case (result < 16):
var rating = 'You are severely underweight';
break;
case (result > 16) && (result < 18.5):
var rating = 'You are underweight';
break;
case (result > 18.5) && (result < 25):
var rating = 'You are healthy';
break;
case (result > 25) && (result < 30):
var rating = 'You are overweight';
break;
case (result > 30) && (result < 35):
var rating = 'You are moderately obese';
break;
case (result > 80):
var rating = 'This result seems unlikely, please check that the information you have entered is correct';
break;
}
$('#result').html('Your BMI is ' + result.toFixed(1) + '. ' + rating + '.');
});
JS Fiddle
http://jsfiddle.net/o12xpy2s/
Change:
switch(result) {
...to:
switch(true) {
Your switch cases are all true or false conditions. So set your switch expression switch(expression) to one or the other. Here you're looking for the true condition of the listed cases.
I'm new to javascript and I'm having a hard time figuring out how to get this factorial function to work. Here's my code now.
var x = prompt("Enter a number"); {
function fact(x) {
if (x < 0) {
return ("Enter a positive integer");
}
else {
return (x * fact(x-1))
}
}
}
var result = fact(x)
document.write("The factorial of" + x + "is" + result);
Thanks for the help!
your base case is wrong for a recursive factorial. change it to
function fact(x) {
if (x <= 1) {
return 1
}
else {
return (x * fact(x-1))
}
}
Your definition of factorial is wrong. The traditional recursive definition of factorial is:
F(x) => x == 1 ? 1 : x * F(x-1)
Or you can use the iterative definition
F(x) => var i = 1; for (j = 1..x) i = i * j
In javascript, the recursive version would be:
function factorial (x) {
if (x == 1) return x;
return x * factorial(x-1);
}
The iterative version would be:
function factorial (x) {
var result = 1;
for (var y = 1; y <= x; y++) {
result = result * y;
}
return result;
}
You can add the negative number check in the above functions. But in my opinion that would obscure the purpose of the function (which is to implement the traditional definition of factorial). A better approach is to move the negative number if() check outside of the factorial function. The if (x < 0) check has its own purpose that is separate from calculating factorials: input validation.
In every recursive function, there exists a stopping condition (in your case its if(x<=1)) without which, the function would go to infinite recursion. You had not added that stopping condition. Following is the working updated program:
var x = prompt("Enter a number"); {
function fact(x) {
if (x < 0) {
return ("Enter a positive integer");
}
else if(x <=1){
return 1;
}
else {
return (x * fact(x-1))
}
}
}
var result = fact(x)
document.write("The factorial of " + x + " is " + result);
In addition to fixing the flawed algorithm, I recommend moving your prompt into its own function for separation of concerns.
I also like the idea of using a while statement for this as well as doing a parseInt on the input:
function fact(x) {
while (x > 1) {
return (x * fact(x-1));
}
return x;
}
function doFact() {
var x = parseInt(prompt("Enter a positive integer"));
if (x < 1) {
doFact();
} else {
var result = fact(x);
alert("The factorial of " + x + " is " + result);
}
}
doFact();