Am i missing (not covering) any cases in this code (JavaScript)? - javascript

function Scholarship(input){
let income = input.shift();
let avgGrade = input.shift();
let minSalary = input.shift();
let isExcellent = false;
let isSocial = false;
let socialSch = 0 ;
let excellentSch = 0 ;
if (avgGrade >= 5.50) {
isExcellent = true;
excellentSch = avgGrade * 25;
}
if (income <= minSalary && avgGrade >= 4.50) {
isSocial = true;
socialSch = minSalary * 0.35;
}
if ((isSocial == false) && (isExcellent == false)){
console.log("You cannot get a scholarship!");
} else if (excellentSch >= socialSch){
console.log(`You get a scholarship for excellent results ${Math.floor(excellentSch)} BGN`);
} else if (socialSch > excellentSch){
console.log(`You get a Social scholarship ${Math.floor(socialSch)} BGN`);
}
}
Scholarship([number, number, number]);
All input numbers(data) are positive.
There should be a mistake somewhere in my logic!
Maybe i am missing to check for some other cases.

Related

Why does my calculation function not run properly?

I need to create a BAC calculator in JavaScript. When I run the code, the form validation works but the calculate function doesn't seem to run.
function validateForm() {
let weight = document.getElementById("weight").value;
let beer = document.getElementById("beer").value;
let wine = document.getElementById("wine").value;
let liquor = document.getElementById("liquor").value;
let hours = document.getElementById("hours").value;
if (weight <= 0){
alert("Weight must be more than zero")
return false;
}
else if (beer<0 || wine<0 || liquor<0 || hours<0){
alert("Number must be zero or higher")
return false;
}
else if(isNaN(weight)||isNaN(beer)||isNaN(wine)||isNaN(liquor)||isNaN(hours)){
alert("Answer must be a number")
return false;
}
else if (weight == null||beer == null||wine == null||liquor == null||hours == null){
alert("All fields must be filled")
return false;
}
else{
return calculate;
}
}
function calculate() {
let weight = document.getElementById("weight").value;
let beer = document.getElementById("beer").value;
let wine = document.getElementById("wine").value;
let liquor = document.getElementById("liquor").value;
let hours = document.getElementById("hours").value;
let answer = (((((beer * 0.54)+(wine*0.6)+(liquor*0.6))*7.5)/weight)-(hours*0.015)).toFixed(3)
document.getElementById("bac").value = answer;
document.getElementById("answer").append(answer);
return answer;
}
If anyone has any answers I'd be more than happy. Thank you.
In the validateForm()-method, try return calculate();

not going to the if statement in javascript

everything is working properly only the control is not moving to the if statement
let fnum, snum, operator;
const op = ["+", "-", "*", "/", "%"];
let fnumUi = document.getElementById("fnumUI");
let snumUi = document.getElementById("snumUI");
let opUi = document.getElementById("opUI");
var input = document.getElementById("user_input");
let scoreUi = document.getElementById("score");
input.addEventListener("keypress", myFunction(event));
function myFunction(event) {
let answer = 8;
if (event.keyCode === 13) {
let user_ans = Number(input.value);
input.value = '';
fnum = Number(Math.floor(Math.random() * 20));
snum = Number(Math.floor(Math.random() * 20));
operator = op[Math.floor(Math.random() * op.length)];
fnumUi.innerHTML = fnum;
snumUi.innerHTML = snum;
opUi.innerHTML = operator;
if (operator === "+") {
answer = fnum + snum;
} else if (operator === "-") {
answer = fnum - snum;
} else if (operator === "*") {
answer = fnum * snum;
} else if (operator === "/") {
answer = fnum / snum;
} else {
answer = fnum % snum;
}
if (answer === user_ans) {
scoreUi.innerHTML = Number(scoreUi.innerHTML) + 3;
} else {
scoreUi.innerHTML = scoreUi.innerHTML - 1;
}
}
}
answer is updating but for this part of code
if (answer === user_ans) {
scoreUi.innerHTML = Number(scoreUi.innerHTML) + 3;
} else {
scoreUi.innerHTML = scoreUi.innerHTML - 1;
}
even when i write the correct answer it moves to else statement. not getting into if statement
so instead of adding 3 in score it is deducting 1 from the score.
You need to pass the function itself rather than the results of its call.
input.addEventListener("keypress",myFunction);

making custom validation for password field in react

I am making a custom registration page with only 2 values Email and Password, later I will add confirm password as well, for my password field I have some restrictions and I am using some regex and also some custom made code to make the validation.
this is my validateField:
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
let passwordValid = this.state.passwordValid;
//let passwordValidConfirm = this.state.passwordConfirmValid;
switch(fieldName) {
case 'email':
emailValid = value.match(/^([\w.%+-]+)#([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.email = emailValid ? '' : ' is invalid';
break;
case 'password':
passwordValid = (value.length >= 5 && value.length <= 32) && (value.match(/[i,o,l]/) === null) && /^[a-z]+$/.test(value) && this.check4pairs(value) && this.check3InRow(value);
fieldValidationErrors.password = passwordValid ? '': ' is not valid';
break;
default:
break;
}
this.setState({formErrors: fieldValidationErrors,
emailValid: emailValid,
passwordValid: passwordValid,
//passwordValidConfirm: passwordValidConfirm
}, this.validateForm);
}
as you can see for
passwordValid
I have made some methods, this one
check3InRow
doesnt work the way I want it to work, this one makes sure, you have at least 3 letters in your string that are in a row so like "abc" or "bce" or "xyz".
check3InRow(value){
var counter3 = 0;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if((lastC + 1) === value.charCodeAt(i)){
counter3++;
if(counter3 >= 3){
alert(value);
return true;
}
}
else{
counter3 = 0;
}
lastC = value.charCodeAt(i);
}
return false;
}
this doesnt work correctly so it should accept this:
aabcc
as a password but not:
aabbc
You are starting your counter from 0 and looking for greater than equal to 3 which will never be 3 for 3 consecutive characters. Rest everything is fine with your code.
check3InRow(value) {
var counter3 = 1;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
alert(value);
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}
Can we not do a simple version of that function? Like
function check3InRow2(value){
for (var i = 0; i < value.length-2; i++) {
const first = value.charCodeAt(i);
const second = value.charCodeAt(i+1);
const third = value.charCodeAt(i+2);
if(Math.abs(second - first) === 1 && Math.abs(third-second) === 1){
return true;
}
}
return false;
}
I mean complexity wise it is O(N) so maybe we can give this a try
Also adding the your function. When you are AT a char then you should consider counter with 1. Because if another one matches it will be 2 consecutive values.
function check3InRow(value) {
var counter3 = 1;
var lastC = value.charCodeAt(0);
for (var i = 1; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}

Javascript Check variable.Then gain ++ per second

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

Categories

Resources