Create a calculation program that will be displayed by the browser - javascript

My program looks good to me but the retuned value is "undefinied" ... do you understand why?
function addition(nombreA,nombreB){
return nombreA + nombreB;
}
function soustraction(nombreA,nombreB){
return nombreA - nombreB;
}
function multiplication(nombreA,nombreB){
return nombreA * nombreB ;
}
function division(nombreA,nombreB){
return nombreA / nombreB ;
}
do {
var calculChoice = prompt("What do you want to do ?\n\n 1 - Addition\n 2 - Soustraction\n 3 - Multiplication\n 4 - Division");
}while(calculChoice != 1 && calculChoice != 2 && calculChoice != 3 && calculChoice != 4);
console.log(calculChoice);
do {
var premierNombre = prompt("entrez votre premier nombre");
var deuxiemeNombre = prompt("entrez votre second nombre");
} while (isNaN(premierNombre)||isNaN(deuxiemeNombre));
console.log(premierNombre,deuxiemeNombre);
switch(calculChoice) {
case 1:
var resultat = addition(premierNombre,deuxiemeNombre);
break;
case 2:
resultat = soustraction(premierNombre,deuxiemeNombre);
break;
case 3:
resultat = multiplication(premierNombre,deuxiemeNombre);
break;
case 4:
resultat = division(premierNombre,deuxiemeNombre);
break;
}
alert(`voici le rรฉsultat = ${resultat}`);
The switch statement will determine which calculation to perform by writing (1,2,3,4).
The first instruction (do while) allows you to enter the numbers 1,2,3,4. If the user does not write these numbers, the instruction executes again.
In the second statement (do while), if the user does not enter a number, it executes again.
Thank you for your time :)

prompt() function returns the result as a string, and not as a number. So you must convert each to integer using parseInt(number). If you don't do that, both your operator and the numbers are strings.
do {
var calculChoice = parseInt(prompt("What do you want to do ?\n\n 1 - Addition\n 2 - Soustraction\n 3 - Multiplication\n 4 - Division"));
} while(calculChoice != 1 && calculChoice != 2 && calculChoice != 3 && calculChoice != 4);
console.log(calculChoice);
do {
var premierNombre = parseInt(prompt("entrez votre premier nombre"));
var deuxiemeNombre = parseInt(prompt("entrez votre second nombre"));
} while (isNaN(premierNombre)||isNaN(deuxiemeNombre));

change your switch by:
switch(parseInt(calculChoice))) {
case 1:
var resultat = addition(premierNombre,deuxiemeNombre);
break;
case 2:
resultat = soustraction(premierNombre,deuxiemeNombre);
break;
case 3:
resultat = multiplication(premierNombre,deuxiemeNombre);
break;
case 4:
resultat = division(premierNombre,deuxiemeNombre);
break;
}
calculChoice is a string, and yu need parse to int

Resultat is also declared in the first switch statement case and it cant be used outside of that. You need to declare resultat before the switch statement.
let resultat=''
switch(calculChoice) {
case 1:
resultat = addition(premierNombre,deuxiemeNombre);
break;
case 2:
resultat = soustraction(premierNombre,deuxiemeNombre);
break;
case 3:
resultat = multiplication(premierNombre,deuxiemeNombre);
break;
case 4:
resultat = division(premierNombre,deuxiemeNombre);
break;
}

Related

How can i check two variables in a switch-case statement?

The question is something like this.
You are given a cubic dice with 6 faces. All the individual faces have a number printed on them. The numbers are in the range of 1 to 6, like any ordinary dice. You will be provided with a face of this cube, your task is to guess the number on the opposite face of the cube.
Ex:
Input:
N = 6
Output:
1
Explanation:
For dice facing number 6 opposite face
will have the number 1.
I did it using a normal switch-case by checking all six faces and returning the respective die face number value, which passed my test cases. However, I need to simplify the code. Is it possible for me to do so?
oppositeFaceOfDice(N) {
//code here
switch(N){
case 1:return 6;
break;
case 6:return 1;
break;
case 2:return 5;
break;
case 5:return 2;
break;
case 3:return 4;
break;
case 4:return 3;
break;
default: return -1;
}
}
oppositeFaceOfDice(N) {
switch(N){
case 1||6 : return 6?1:6;
break;
case 2||5: return 2?5:2;
break;
case 3||4: return 4?3:4;
break;
}
}
Use an object literal instead of a switch statement:
function oppositeFaceOfDice(N) {
return {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}[N];
}
Or use #DavidThomas' suggestion above which is particularly clever:
function oppositeFaceOfDice(N) {
if(N < 1 || N > 6) return undefined;
return 7 - N;
}
Other than rewriting the codes, since in your case, the codes are very clear and easy to debug, you can remove the break statement since it's not necessary.
oppositeFaceOfDice(N) {
//code here
switch(N){
case 1:return 6;
case 6:return 1;
case 2:return 5;
case 5:return 2;
case 3:return 4;
case 4:return 3;
}
}

How to create a simple calculator using switch case and function using Javascript

I'm new to Javascript and just finished learning switches and conditionals and I wanted to create my calculator where it first asks the user what they want to do and gets the two digits from them and goes ahead and alerts them with an answer. But every time I try to run the function it gives me an undefined error enter code here
let tell = prompt("What would you like to do (*,/,+,-)");
let dig1 = prompt("Enter first Number");
let dig2 = prompt("Enter second Number")
function calculate(a,b) {
let answer = tell;
switch (a,b) {
case "*":
answer = a * b;
break;
case "/":
answer = a / b;
break;
case "+":
answer = a + b;
break;
case "-":
answer = a - b;
break
}
}
alert(calculate(dig1,dig2))
let tell = prompt("What would you like to do (*,/,+,-)");
let dig1 = prompt("Enter first Number");
let dig2 = prompt("Enter second Number")
function calculate(a,b) {
// check the value of the `tell` is one of these cases and return the result.
switch (tell) {
case "*":
return a * b;
case "/":
return a / b;
case "+":
return a + b;
case "-":
return a - b;
default:
return "You didn't a correct opertor"
}
}
alert(calculate(+dig1, +dig2))

Card Counting with Switch instead of If Else if. Why do I not need to also use RETURN?

I'm a beginner in javascript, so apologies in advanced if this is a dumb question. So, I've noticed that this question has been asked before, but that question was using IF ELSE statements. I'm trying to do it with SWITCH instead.
What i wanted to know is whether i need to also type in RETURN before count++ or count-- inside the SWITCH. I was using a website that provided this question, and my only error was that i used RETURN. The other post used IF ELSE IF and used RETURN.
Can anybody explain why i didn't need to use RETURN?
let count = 0;
function cc(card) {
switch (card){
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 7: case 8: case 9:
count;
break;
case 10: case "J": case "Q": case "K": case "A":
return count--;
break;
}
if (count>0){
return count+" Bet";
} else {
return count+" Hold";
}
}
Update
Do not add return to a switch()'s case block
Interrupting the flow gives you no advantage and more than likely error prone code that will not log any runtime errors.
In Example C are three functions:
Function
Description
Icon
A(card)
The original version of cc(card) without the added returns
๐Ÿ‘
B(card)
The modified version of cc(card) with returns short circuiting each case
โ›”
C(card)
The modified version of B(card) with prefixed operators that fix B(card)
โš ๏ธ
switch() is Fragile
A return before the break is a short circuit. Short circuit in programming context is inserting an early termination of a function/method when a condition is meet. I use this technique frequently but never in a switch(). switch() is a very readable yet bulky function if you deviate from how it's normally used it will usually cause a hiccup -- something inaccurate or incorrect and too slight to notice since it's not a runtime error.
Take for instance the line marked with a warning sign โš ๏ธ in Example A (also abstracted in Figure I)
Figure I
return count--;
break;
So any 10 or face card is short circuited so it never reaches break nor will it reach the last condition that determines whether to bet
or hold which is the whole point of this function. Now if we were to pass an Aโ™ค:
Figure II
cc('A');
// returns a 0 / expected -1
Why did it not decrement count? Because it never got the chance to be evaluated due to being short circuited. Originally, all cards went through the switch got it's value then when it reached the last condition, it would be evaluated and it's current values set to 1, 0, or -1. If you have your heart set on using returns before a break, change the counters from post to pre (see Figure III).
Figure III
return ++counter;
When the in/decrement is prefixed to the value, it is evaluated before it's stored so you'll get accurate results. Like I said, there's no point in using the switch() if return is used within it.
Example A is the OP (Original Post)
Example B is a refactor of OP
Example C is a side-by-side comparison between OP with short circuit ๐Ÿ‘Ž and OP without short circuit ๐Ÿ‘
Example A
Original Answer
let count = 0;
function cc(card) {
switch (card) {
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 7:
case 8:
case 9:
count;
break;
case 10:
case "J":
case "Q":
case "K":
case "A":
return count--; // โš ๏ธ
break;
}
if (count > 0) {
return count + " Bet";
} else {
return count + " Hold";
}
}
console.log(cc('A'));
Example B
More Blackjack Rules Applied
/**
* #desc - Formats output to console
* #param {any} data - Limited like JSON
*/
const msg = data => console.log(JSON.stringify(data));
/**
* #desc - Given an unknown amount of numbers and
* strings that represent a set of 52 playing
* cards, it'll calculate:
* score points[0]
* hint points[1]
* aces points[2]
* #param {array<rest>} cards - One or more numbers and
strings.
* #return {array<number>} An array of 3 numbers
* see #desc
*/
const score = (...cards) => {
let tuple = [...cards].reduce((points, current) => {
points[0] += current === 'A' ? 11 : typeof current == 'string' ? 10 : current;
points[1] += current < 7 ? 1 : current > 9 ? -1 : 0;
return points;
}, [0, 0]);
let aces = [...cards].filter(c => c === 'A').length;
tuple.push(aces);
return tuple;
}
/**
* #desc - Given an array of 3 numbers, it calculates,
* adjusts, and determines the flow of a
* blackjack game
* #param {array<number>} score - The output of score()
* #return {string} A msg to inform the player of
* current score, a suggestion of what
* to do next, or when the player busts
*/
const hand = score => {
while (score[0] > 21) {
if (score[2] > 0) {
score[2] -= 1;
score[1] += 1;
score[0] -= 10;
} else {
return msg(`${score[0]}, bust!`);
}
}
if (score[0] === 21) {
return msg('BLACKJACK!');
}
let action = score[1] > 0 ? 'make a wager' : 'stand';
return msg(`${score[0]}, you should ${action}.`);
}
hand(score('A', 4, 10));
hand(score(2, 9, 3, 9));
hand(score(10, 'K'));
hand(score(6, 2));
hand(score('A', 'K'));
Example C
Wrong vs. Right
let count = 0;
let countA = 0;
let countB = 0;
let countC = 0;
function A(card) {
console.info('Test ' + count + ' ============================');
console.log('------------A๐Ÿ‘-------------');
console.log('inA: ' + countA + ' Card: ' + card);
switch (card) {
case 2:
case 3:
case 4:
case 5:
case 6:
countA++; // ๐Ÿ‘
console.log('A++: ' + countA);
break;
case 7:
case 8:
case 9:
countA; // ๐Ÿ‘
console.log('A: ' + countA);
break;
case 10:
case "J":
case "Q":
case "K":
case "A":
countA--; // ๐Ÿ‘
console.log('A--: ' + countA);
break;
}
if (countA > 0) {
return countA + " Bet";
} else {
return countA + " Hold";
}
}
function B(card) {
console.log('------------Bโ›”-------------')
console.log('inB: ' + countB + ' Card: ' + card);
switch (card) {
case 2:
case 3:
case 4:
case 5:
case 6:
console.log('B++: ' + countB);
return countB++; // โ›”
break;
case 7:
case 8:
case 9:
console.log('B: ' + countB);
return countB; // โ›”
break;
case 10:
case "J":
case "Q":
case "K":
case "A":
console.log('B--: ' + countB);
return countB--; // โ›”
break;
}
if (countB > 0) {
return countB + " Bet";
} else {
return countB + " Hold";
}
}
function C(card) {
console.log('------------Cโš ๏ธ-------------');
console.log('inC: ' + countC + ' Card: ' + card);
switch (card) {
case 2:
case 3:
case 4:
case 5:
case 6:
console.log('--C: ' + countC + 'โš ๏ธ');
return ++countC; // โš ๏ธ
break;
case 7:
case 8:
case 9:
console.log('C: ' + countC);
return countC; // โš ๏ธ
break;
case 10:
case "J":
case "Q":
case "K":
case "A":
console.log('--C: ' + countC + 'โš ๏ธ');
return --countC; // โš ๏ธ
break;
}
if (countC > 0) {
return countC + " Bet";
} else {
return countC + " Hold";
}
}
document.forms.bj.oninput = hit;
document.forms.bj.onreset = reset;
function hit(e) {
const IO = this.elements;
let draw = IO.draw.value;
let card = isNaN(draw) ? draw : +draw;
let a = A(card);
let b = B(card);
let c = C(card);
IO.A.value = a;
IO.B.value = b;
IO.C.value = c;
count++;
}
function reset(e) {
count = 0;
countA = 0;
countB = 0;
countC = 0;
}
html {
font: 300 1.5ch/1.2 'Segoe UI';
}
#table {
display: flex;
max-width: max-content;
}
legend {
font-size: 1.25rem;
}
select,
input {
display: inline-flex;
font: inherit;
}
label,
select,
input,
output {
display: block;
margin-bottom: 0.5rem;
}
output {
font-weight: 900;
text-align: center;
}
#B {
color: red;
}
.as-console-row::after {
width: 0;
font-size: 0;
}
.as-console-row-code {
width: 100%;
word-break: break-word;
}
.as-console-wrapper {
min-height: 100% !important;
max-width: 50%;
margin-left: 50%;
}
<form id='bj'>
<fieldset id='table'>
<legend>Blackjack</legend>
<label class='IN'>
<select id='draw'>
<option selected>Draw</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='J'>Jack</option>
<option value='Q'>Queen</option>
<option value='K'>King</option>
<option value='A'>Ace</option>
</select>
<input type='reset'>
</label>
<fieldset>
<label>
Original: ๐Ÿ‘<br>
<output id='A'> </output>
</label>
<label>
Short Circuits: โ›”<br>
<output id='B'> </output>
</label>
<label>
Short Circuits<br>Prefixed Operators: โš ๏ธ<br>
<output id='C'> </output>
</label>
</fieldset>
</fieldset>
</form>

How to find maximum between two numbers in javascript using switch case?

I am trying to run with this code block but it does not work
Switch (num1>num2) {
case 0:
document.write(num2);
break;
case 1:
document.write(num1);
break;
}
You could use something simple as Math.max(5, 10);
const numOne = 5;
const numTwo = 10;
console.log(`Bigger number is: ${Math.max(numOne, numTwo)}`);
Or if you absolutely 'have to' use switch statement, you can try something like this:
const numOne = 5;
const numTwo = 10;
switch(true) {
case (numOne > numTwo):
console.log(`Bigger number is ${numOne}`);
break;
case (numOne < numTwo):
console.log(`Bigger number is ${numTwo}`);
break;
case (numOne === numTwo):
console.log(`${numOne} is equal to ${numTwo}`);
break;
default: console.log(false, '-> Something went wrong');
}
Logical operations return boolean on Javascript.
document.write writes HTML expressions or JavaScript code to a document, console.log prints the result on the browser console.
switch (num1>num2) {
case true:
console.log(num1);
break;
case false:
console.log(num2);
break;
}
switch (with a lower case s) uses strict comparison === so the value of a boolean like 11 > 10 will never === 0 or 1.
You need to test for the boolean if you want to do it this way:
let num1 = 10
let num2 = 20
switch (num1>num2) {
case false:
console.log(num2);
break;
case true:
console.log(num1);
break;
}
If for some reason you were given numbers you could explicitly cast them to booleans with something like case !!0: but that starts to get a little hard on the eyes.
If your goal is to find the max of two numbers, Math.max(num1, num2) is hard to beat for readability.
You would just use the greater than / less than inside of the switch statement.
var x = 10;
var y = 20;
switch(true) {
case (x > y):
console.log(x);
break;
case ( y > x):
console.log(y);
break;
}

how to take information from custom method and apply it to another method inside my constructor function javascript?

Okay so I was trying to think of a good example, and so I created a constructor function about precious metals. The constructor takes in type of metal and weight. I have two methods. One method determines if the precious metal (gold or silver) is real and the other calculates the value based on spot price. (I know the spot price is wrong, this is just an example anyway).
Suppose a customer brought in a silver piece that is 80% silver. Because its 80% silver I want to apply that to my metalValue method. How would I do that.
Here is the code. (JSFiddle provided for your convience http://jsfiddle.net/bwj3fv12/).
This will help me understand constructors better.
HTML
<div id="testDiv">test Div</div>
<div id="testDiv2">test Div2</div> <br /><br />
JavaScript
var PreciousMetals = function(metal, weight){
this.metal = metal;
this.weight = weight; //weight in ounces
this.authentic = function(colorTest){
var metalPurity;
var zero = "";
if (this.metal == "silver"){
switch(colorTest){
case "brightred":
metalPurity = 1;
break;
case "darkred":
metalPurity = 0.925;
break;
case "brown":
metalPurity = 0.80;
break;
case "green":
metalPurity = 0.50;
break;
default:
metalPurity = 0;
}
}else if(this.metal == "gold"){
switch(colorTest){
case "green":
metalPurity = "base metal or gold plated";
break;
case "milk colored":
metalPurity = "gold plated sterling silver";
break;
case "no color":
metalPurity = "real gold";
break;
default:
metalPurity = "Could be a fake, try different test";
}
}
return metalPurity;
}
this.metalValue = function(metal){
var sum = 0;
var spotPrice;
if (this.metal == "gold"){
spotPrice = 1000;
}else if(this.metal == "silver"){
spotPrice = 15;
}
sum = spotPrice * this.weight;
return sum;
}
}
var customerCindy = new PreciousMetals("silver", 2);
document.getElementById('testDiv').innerHTML = customerCindy.authentic("brown");
document.getElementById('testDiv2').innerHTML = customerCindy.metalValue(); //The result I would like would be 24 of course.
Now I realize I could do it this way:
document.getElementById('testDiv2').innerHTML = customerCindy.metalValue() * customerCindy.authentic("brown");
However the goal here is to take in the information from the authentic method and use that to help me calculate the metal Value in the metalValue method.
If you'd like to keep the logic of these two methods separate in your constructor function, you could include a third method that performs the task of multiplying the two results.
var PreciousMetals = function(metal, weight){
this.metal = metal;
this.weight = weight; //weight in ounces
this.authentic = function(colorTest){
var metalPurity;
var zero = "";
if (this.metal == "silver"){
switch(colorTest){
case "brightred":
metalPurity = 1;
break;
case "darkred":
metalPurity = 0.925;
break;
case "brown":
metalPurity = 0.80;
break;
case "green":
metalPurity = 0.50;
break;
default:
metalPurity = 0;
}
}else if(this.metal == "gold"){
switch(colorTest){
case "green":
metalPurity = "base metal or gold plated";
break;
case "milk colored":
metalPurity = "gold plated sterling silver";
break;
case "no color":
metalPurity = "real gold";
break;
default:
metalPurity = "Could be a fake, try different test";
}
}
return metalPurity;
}
this.metalValue = function(){
var sum = 0;
var spotPrice;
if (this.metal == "gold"){
spotPrice = 1000;
}else if(this.metal == "silver"){
spotPrice = 15;
}
sum = spotPrice * this.weight;
return sum;
}
this.netValue = function(colorTest){
return this.authentic(colorTest) * this.metalValue();
}
}
Here's a working JSFiddle - https://jsfiddle.net/bwj3fv12/
If you wanted to update metalValue to include the results from the purity check, you could just update
this.metalValue = function(colorTest){
// ...
sum = spotPrice * this.weight * this.authentic(colorTest);
return sum;
}
and call it with
customerCindy.metalValue('brown');
Since this is just an example, there's no reason to worry about it, but presumably the purity in the real world would be just as much an instance property as the metal and the weight, and wouldn't actually be a transient value for a method like this. But that's neither here nor there.

Categories

Resources