how I can cancel the value of the entire instruction - javascript

let mood = 'sleepy';
let tirednessLevel = 6;
if (mood === 'sleepy' || tirednessLevel > 8) {
console.log('time to sleep');
} else {
console.log('not bed time yet');
}
How I can cancel the value of the entire instruction with! ??

Need More Info about what you want but this may help you to know
let mood = 'sleepy';
let tirednessLevel = 6;
function check() {
if (mood=== 'sleepy' || tirednessLevel > 8){
return 'time to sleep';
} else{
return 'not bed time yet';
}
return '';
}
console.log(check())

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();

IF ELSE Statement not working in a loop with Images and Genders

I have a code taken from github. It should generate random faces from images, works fine. I now wanted to add a new gender to the code. At the moment it has "Male" and "Female" I wanted to add "Zombie" and "Alien".
Now I added the gender like the Male and Female are added in the code, this also works. The point where I can't find a solution is, that I added an else if condition to make the alien and zombie more rare than male and female, but this isn't working. The code only assigns a random gender face and there is no difference how often a gender appears.
I added the code below, I'm sorry that it's not reproducable. you can get the working code here:
Master file, Github
if (ranint > 500 <998) return "Female";
else if (ranint < 2) return "Zombie";
else if (ranint > 998) return "Alien";
else return "Male";
}
async function saveFaceByCode(codeArr, outFile) {
let images = [];
for (let i=0; i < partTypes.length; i++) {
if (codeArr[i] != 0) {
const img = {
src: `${partFolder}/${partTypes[i].name}${codeArr[i]}${ext}`,
offsetX: partTypes[i].offset.x,
offsetY: partTypes[i].offset.y,
}
images.push(img);
}
}
// Generate image
await mergeImagesToPng(images, outFile);
}
async function generateFaces() {
// Array that lists all characters
let characters = [];
// Save attributes and generate map of attributes to saved array index
let attrArray = [];
let attrMap = {};
let attrFreq = {};
let attrCount = 0;
for (let i=0; i < partTypes.length; i++) {
for (let j=1; j<=partTypes[i].count; j++) {
if (partTypes[i].attrNames[j-1].length > 0) {
attrArray.push(partTypes[i].attrNames[j-1]);
attrMap[partTypes[i].attrNames[j-1]] = attrCount;
attrFreq[partTypes[i].attrNames[j-1]] = 0;
attrCount++;
}
}
}
let attrjs = `const attributes = ${JSON.stringify(attrArray)};`;
attrjs += "\n\nmodule.exports.attributes = attributes;";
fs.writeFileSync(outputAttributesJS, attrjs);
// "Code array" contains the code of current "face"
// Initialize it to the first "face"
let codeArr = [];
for (let i=0; i < partTypes.length; i++) {
if (partTypes[i].required)
codeArr.push(1);
else
codeArr.push(0);
}
let imgCount = 0;
// In the loop generate faces and increase the code by one
let exhausted = false;
while (!exhausted) {
// Check if combination is valid
let gender = detectGender(codeArr);
let valid = checkAttributeCompatibility(codeArr);
// Skip faces randomly to get close to desired count
const r = (getRandomInt(1000)+1)/1200;
// const r = 0;
if ((r <= desiredCount/totalFaces) && (gender != "Invalid") && (valid)) {
// Generate and save current face
await saveFaceByCode(codeArr, `${outputFolder}/image${imgCount}${ext}`);
// Add character with accessories
c = {
id: imgCount,
gender: gender,
attributes: []
};
for (let i=0; i < partTypes.length; i++) {
if (partTypes[i].attrNames.length != 0)
if (codeArr[i] != 0) {
let attrName = partTypes[i].attrNames[codeArr[i]-1];
if (attrName.length > 0) {
c.attributes.push(attrMap[attrName]);
attrFreq[attrName]++;
}
}
}
characters.push(c);
imgCount++;
} else {
// console.log(`Skipping. r = ${r}, gender = ${gender}, codeArr=${codeArr}`);
}
// Increate code by 1
let canIncrease = false;
for (let i=0; i < partTypes.length; i++) {
if (codeArr[i] < partTypes[i].count) {
canIncrease = true;
codeArr[i]++;
for (let j=i-1; j>=0; j--) {
if (partTypes[j].required)
codeArr[j] = 1;
else
codeArr[j] = 0;
}
break;
}
}
if (!canIncrease) exhausted = true;
if (imgCount == desiredCount) break;
}
// Save characters' JSON
fs.writeFileSync(outputCharacterJSON, JSON.stringify(characters));
console.log("Total generated characters: ", imgCount);
console.log("Attribute frequencies: ", attrFreq);
}
async function generateManually() {
// Женин любимый
code = [1, 5, 2, 3, 1, 1, 5, 1];
await saveFaceByCode(code, "test.png");
let punks = require("./generated_faces/characters.json");
c = {
id: 10000,
gender: "Male",
attributes: [3,7,13,21,29]
};
punks.push(c);
fs.writeFileSync("characters.json", JSON.stringify(punks));
}
async function main() {
await generateFaces();
// await generateManually();
}
main();
// function test() {
// code = [1, 6, 2, 4, 4, 1, 8, 1];
// console.log(detectGender(code));
// }
// test();
The part I edited is:
function detectGender(codeArr) {
let male = false;
let female = false;
let zombie = false;
let alien = false;
for (let i=0; i < partTypes.length; i++) {
if (codeArr[i] != 0) {
const attrGender = partTypes[i].attrSex[codeArr[i]-1];
if (attrGender == "m") male = true;
if (attrGender == "f") female = true;
if (attrGender == "z") zombie = true;
if (attrGender == "a") alien = true;
}
}
if (male && female) return "Invalid";
if (male && zombie) return "Invalid";
if (male && alien) return "Invalid";
if (female && alien) return "Invalid";
if (female && zombie) return "Invalid";
if (alien && zombie) return "Invalid";
if (male) return "Male";
if (female) return "Female";
if (zombie) return "Zombie";
if (alien) return "Alien";
var ranint = Math.floor(Math.random() * 1000) + 1;
if (ranint > 500 <998) return "Female";
else if (ranint < 2) return "Zombie";
else if (ranint > 998) return "Alien";
else return "Male";
}
I know that this is not coded well... I'm just a beginner trying to modify something found online.
For starters the following block will in all likelihood return a String of sorts - first one that evaluates True:
if (male && female) return "Invalid";
if (male && zombie) return "Invalid";
if (male && alien) return "Invalid";
if (female && alien) return "Invalid";
if (female && zombie) return "Invalid";
if (alien && zombie) return "Invalid";
if (male) return "Male";
if (female) return "Female";
if (zombie) return "Zombie";
if (alien) return "Alien";
so the random code after that will never run.
Also, as mentioned the following should read (I presume)
if (ranint > 500 && ranint < 998) return "Female";
I would say the problem lies in the last lines, those else if are invalid syntax. I'd write your function like this:
if (ranint > 500 && ranint < 998) {
return "Female"
} else if (ranint < 2) {
return "Zombie"
} else if (ranint > 998) {
return "Alien"
} else {
return "Male"
}
If you open the console in your browser (hitting F12 most likely) and write this function:
function getType() {
let ranint = Math.floor(Math.random() * 1000) + 1
if (ranint > 500 && ranint < 998) {
return "Female"
} else if (ranint < 2) {
return "Zombie"
} else if (ranint > 998) {
return "Alien"
} else {
return "Male"
}
}
And execute it by calling getType() you'll get Female most of the time, at least that is my experience.
And as mentioned in #batman567 answer, there are elements within your function that are making this code unreachable, namely:
if (male && female) return "Invalid";
if (male && zombie) return "Invalid";
if (male && alien) return "Invalid";
if (female && alien) return "Invalid";
if (female && zombie) return "Invalid";
if (alien && zombie) return "Invalid";
if (male) return "Male";
if (female) return "Female";
if (zombie) return "Zombie";
if (alien) return "Alien";
If any of these conditions evaluates to True, the function will return at that point (it will return wathever value is written after the return) and the rest of the function won't have any effect on the result at all.

Am i missing (not covering) any cases in this code (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.

What am i doing wrong? it wont run thru every condition

I'm trying to have someone guess a number from 1 to 6. I give them two tries if, by the end of the second try, they don't get it, then else will tell them what the number is but it just won't run. what am I doing wrong?
var number = Math.floor(Math.random() *6) +1;
var answer = false;
var guess = prompt('Take a guess, pick a number from 1 to 6');
if(parseInt(guess) === number) {
answer === true;
} else if (parseInt(guess) > number) {
var guessLess = prompt('To high! Guess less');
if (parseInt(guessLess) === number) {
answer === true;
} else if (parseInt(guess) < number) {
var guessMore = prompt('Guess more');
if(parseInt(guessMore) === number) {
answer = true;
}
}
}
if (answer) {
alert('You got it')
} else {
alert('No. The number was ' + number);
}
}
You are using comparison instead of assignment in the below segment
if (parseInt(guessLess) === number) {
answer === true;
Change it to
if (parseInt(guessLess) === number) {
answer = true;

function won't run the second part of the code how do I fix this?

Here is my code
function CheckForm_1() {
var F1 = document.getElementById('srch');
var Lgth = document.getElementById('srch');
if (F1.value == "") {
document.getElementById("Empty_Err");
Empty_Err.style.display = 'inline';
Empty_Err.stylebackgroundColor = 'linen';
return false;
} else {
return true;
}
if (Lgth.value.length > 17 || Lgth.value.length < 4) {
document.getElementById("Length_Err");
Length_Err.style.display = 'inline';
backgroundColor = 'linen';
alert("Search length must be be between 4 and 17");
return false;
} else {
return true;
}
}
I can't get it to check the field length Any ideas on this?
The code will run a check for an empty field just fine.
Returning value will stop execution of a function.
As #Calvin Nunes commented
When you use return, you stop the function execution because you
returned a value, so the function is terminated...that's why you'll
never reach the second if, because in the first if you return or true
or false
function CheckForm_1() {
var F1 = document.getElementById('srch');
var errorMessage = document.getElementById("errorMessage");
if (F1.value == "") {
errorMessage.style.display = 'inline';
errorMessage.style.backgroundColor = 'linen';
errorMessage.innerHTML= "Search field is empty";
} else if (F1.value.length > 17 || F1.value.length < 4) {
errorMessage.style.display = 'inline';
errorMessage.style.backgroundColor = 'linen';
errorMessage.innerHTML = 'Search length must be be between 4 and 17';
} else {
errorMessage.style.display = 'none';
}
}
<input id='srch' type="text" />
<div id="errorMessage" style="display:none">Search field is empty</div><br>
<button type="button" onclick="CheckForm_1()">Submit</button>

Categories

Resources