not converting the int into a string on if statement - javascript

I am trying to convert an int into a str using a if loop! here is my logiv. What is it that I am doing wrong ? Any ideas ?
var waitTime = parseInt("53");
if (waitTime > 20) {
return 'a lot of time'
} else if (waitTime < 20) {
return 'we can wait'
}
console.log(waitTime);
I keep getting

Your code looks mostly correct, including your usage of parseInt, but perhaps you are mixing your return statements with console.log statements?
var waitTime = parseInt("53");
if (waitTime > 20) {
console.log('a lot of time'); // use console.log rather than return
} else if (waitTime < 20) {
console.log('we can wait'); // use console.log rather than return
}
console.log(waitTime);
http://jsbin.com/kebagodura/edit?js,console,output

Alternatively (to Jonathan's answer), put the code in a function and then the returns would make sense. An improved version would see you passing in the wait time as an argument to the function.
function doIt(number) {
// Don't forget the radix on parseInt
var waitTime = parseInt(number, 10);
if (waitTime > 20) {
return 'a lot of time'
} else if (waitTime < 20) {
return 'we can wait'
}
}
var result = doIt('53'); // a lot of time
var result = doIt('12'); // we can wait
DEMO

You could also do it this way- instead of "return" you can do this:
var waitTime = parseInt("53");
if (waitTime > 20) {
waitTime = 'a lot of time';
} else if (waitTime < 20) {
waitTime = 'we can wait';
}
console.log(waitTime);

You simply can do that this way, reassigning the variable values in the if/else clause:
var waitTime = parseInt("53");
if (waitTime > 20) {
waitTime = 'a lot of time';
} else if (waitTime <= 20) {
waitTime = 'we can wait';
}
console.log(waitTime);

You have an error in your code.
return 'a lot of time'
It is trying to return the text a lot of time from a function. but you never created a function so it will throw an error.
Closer to what you want:
function wait(waitTime) {
if (waitTime > 20) {
return 'a lot of time'
} else if (waitTime < 20) {
return 'we can wait'
}
}
console.log(wait(YOUR_WAIT_TIME_HERE));
EDIT You don't need the parseInt function at all. (ie: '25' > 20) implicitly casts '25' to a Number.

Related

Codewars JavaScript fundamental problem help (Arrays)

I've been trying to resolve the following problem:
You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.
Note: you will always receive a valid array containing a random assortment of direction letters ('n', 's', 'e', or 'w' only). It will never give you an empty array (that's not a walk, that's standing still!).
Here is the code I wrote:
function walkTime(walk) {
//insert brilliant code here
var walkLength = walk.length;
if (walkLength === 10) {
return true;
}
else {
return false;
}
}
findEndPosition = (Arr) => {
var y = 0
if (Arr.length > 10) {
return false
}
else {
Arr.forEach((x) => {
if (x === 'n') {
y++;
}
if (x === 's') {
y--;
}
if (x === 'e') {
y++;
}
if (x === 'w') {
y--;
}
})
};
if (y === 0) {
return true;
}
else {
return false;
}
}
const isValidWalk = (walk) => {
if(walkTime(walk) === true && findEndPosition(walk) === true){
return true
}
else {
return false
}
}
console.log(isValidWalk(['w','e','w','e','w','e','w','e','w','e','w','e']));
I keep trying to passing all the tests except for two. Unfortunately it's not telling me what inputs it's using that keep failing :/. Anyone think they know what's going on, this is driving me crazy! Thanks in advance!
If your goal is only to check if the walk will take exactly 10 minutes, it should be enough to test that the walk array is 10 in length and the walk steps are valid. Isn't it so?
In your code, you have a function for solving the end position. There is a clear mistake as steps to west and east are changing the y variable. Is your actual problem more related to this one?
Just wanted to let you guys know I found this solution. It worked through all the tests! I'm sure it could be written a lot better, if you guys got suggestions I'd appreciate it! Anyways here it is!
function walkTime(walk) {
//insert brilliant code here
var walkLength = walk.length;
if (walkLength === 10) {
return true;
}
else {
return false;
}
}
const findEndPosition = (Arr) => {
var y = 0;
var x = 0;
if (Arr.length > 10) {
return false
}
else {
Arr.forEach((movement) => {
if (movement === 'n') {
y++;
}
if (movement === 's') {
y--;
}
if (movement === 'e') {
x++;
}
if (movement === 'w') {
x--;
}
})
};
const newLocation = [x,y];
if (newLocation.toString() === '0,0') {
return true;
}
else {
return false;
}
}
const isValidWalk = (walk) => {
if(walkTime(walk) === true && findEndPosition(walk) === true){
return true
}
else {
return false
}
}
console.log(isValidWalk(['n','s','e','w','n','s','e','w','e','w']));

How to get the result of If/ If else statement

I don't know if I'm overseeing it or what, but I don't know how to get the result of an else if statement, for example, I have this code that I have been practicing:
In this case, the result would be "It's warm!", what I'd like to do is to create a code that would depend on the result, but the result it's not a variable, so how do I create a code responding to what was logged? for example if it logged: "It's warm!" I want to add something like "Turn on the AC." or "Turn on the heater" or something else. How do I do it?
let temperature = 36
if (temperature > 24) {
console.log ("It's warm!");
} else if (temperature < 24) {
console.log ("It's cold!");
} else {
console.log ("It's cool!");
You could just save it as a variable:
let temperature = 36;
const isCold = temperature < 24;
const isWarm = temperature > 24;
if (isWarm) {
console.log("It's warm!");
} else if (isCold) {
console.log("It's cold!");
} else {
console.log("It's cool!");
}
if (isWarm) {
console.log("Turn on the A/C!");
}
you can set your code in the expresion block that are defined with {} after the if condition..
As example:
let temperature = 36;
if (temperature > 24) {
console.log("It's warm!");
console.log("Turn on the AC.");
// You can write coode base in this condition as much you want
// or you can call another function
} else if (temperature < 24) {
console.log("It's cold!");
} else {
console.log("It's cool!");
}
Not quite sure what you mean, but if you want to output the temperature:
let temperature = 36
if (temperature > 24) {
console.log ("It's warm!", temperature, "degrees");
} else if (temperature < 24) {
console.log ("It's cold!", temperature, "degrees");
} else {
console.log ("It's cool!", temperature, "degrees);
Put the result into a variable.
let temperature = 36;
let result = '';
if (temperature > 24) {
result = "It's warm!";
} else if (temperature < 24) {
result = "It's cold!";
} else {
result = "It's cool!";
}
console.log (result);
You can set a variable in a function - pass the temperature into the fucntion and output the result - note the use of the switch statement that compares the inputted temp to the conditions and update the result string. This is what switch statements are for - to provide an alternative to nested or complex if else statments.
function setTemperature(temp){
let result = "It's ";
switch (true) {
case temp > 24:
result += "warm!";
break;
case temp > 12:
result += "cool!";
break;
default:
result += "cold!";
}
return result;
}
console.log( setTemperature(36)); // gives "It's warm!"
console.log( setTemperature(16)); // It's cool!
console.log( setTemperature(6)); //It's cold!
You can make a function like so:
let temperature = 36;
function myFunct(temp){ // "myFunct" can be anything
if (temp > 24) {
return "It's warm!";
} else if (temp < 24) {
return "It's cold!";
} else {
return "It's cool!";
}
}
var t = myFunct(temperature); // get whether it's warm, cold, or cool
console.log(t); // tell the user if it's warm, cold, or cool
// do something!
if(t === "It's warm!"){
// run something here if it's warm
} else if (t === "It's cold!"){
// run something here if it's cold
} else {
// run something here if it's cool
}
Though you could just run something inside the function or original if statement instead.
Hope this helped!

conditional statement if value is greater or less then show error

I am trying to display a warning message if the temperature is higher then 40 or above - 10
but is not working.
I read some websites and in StackOverflow I found this Switch statement for greater-than/less-than to try to solve the problem but I still couldn't find a solution for what might be happening.
Can you help me out?
Many thanks.
function Celsius(kelvin) {
let celsiusTemp = Math.round(kelvin - 273.15);
if (celsiusTemp > 35) {
console.log('too hot, use sunscreen ')
} else
if (celsiusTemp < 5) {
console.log('too cold, get warm ')
} else {
return celsiusTemp + `°C`;
}
};
Celsius(kelvin) {
let celsiusTemp = Math.round(kelvin - 273.15);
if (celsiusTemp < 35 || celsiusTemp > 5) {
return celsiusTemp + `°C`;
}
if (celsiusTemp > 35) {
return celsiusTemp + `°C, too hot, use sunscreen`;
}
if (celsiusTemp < 5) {
return celsiusTemp + `°C,too cold, get warm`;
}
}
//call method Celsius(298) here like this
console.log(this.Celsius(298));
//or
console.log(Celsius(298));

for loop in javascript is skipping else if condition half the time

I'm was just fiddling around with javascript and I wrote function using Math.random that I thought would return a coin-flip. Then I was curious so I ran it through a loop to test how often it flips true/false. I found out my loop is skipping about half of the else if conditions, and was able to verify this by catching them in the errors var. So, why is it doing this?
var truths = 0;
var alternativetruths = 0;
var errors = 0;
function game() {
var score = Math.random()*10;
return score>5;
}
for(i=0;i<999999;i++) {
if (game() === true) {
truths++
} else if (game() === false) {
alternativetruths++
} else {
errors++
}
}
console.log("truths:",truths,"alternativetruths:",alternativetruths,"errors:",errors)
truths: 500393 alternativetruths: 249580 errors: 250026
Your code calls game() twice. If the first call isn't true, then the second might or might not be true.
Just call game() once and assign the result to a variable. Don't make explicit comparisons to true and false; if statements work off boolean values, and your function already returns one of those.
for (var i = 0; i < 999999; i++) {
var result = game();
if (result)
truths++;
else
alternativetruths++;
}
Because you're calling game twice, and thus getting two different random flags.
The minimal change is to remember the number:
for(i=0;i<999999;i++) {
var flag = game();
if (flag === true) {
truths++
} else if (flag === false) {
alternativetruths++
} else {
errors++
}
}
But a couple of other notes:
If flag is a boolean (and it is, it's the result of the > operator), then if (flag === true) is pointless. Just use if (flag). The result of the === operator is a boolean too, so if you don't trust them to be true or false, where do you stop? :-) if ((flag === true) === true)?
Separately, if (flag === false) should just be if (!flag).
If flag is a boolean (and it is), then if you have if (flag), having else if (!flag) and then else doesn't make any sense. There is no way you'll reach that final else. Just if (flag) { } else { } is all you need.
But, game isn't fair, it has a very slight bias toward returning false. Remember, the range returned by Math.random() * 10 is 0 to just under 10, so checking for > 5 means you're skipping the midpoint. Because you're dealing with very small fractional numbers, you don't notice the bias, but it's there; it would be more obvious if you rounded to whole numbers, at which point it would be roughly 40%/60% true/false. You want >= 5 for fair results.
game can rather moer succinctly be written: return Math.random() >= 0.5;.
Because you're not declaring i, you're falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog). Remember to declare your variables.
Re > vs. >=, here's an example where I've rounded to whole numbers to make the effect clearer:
for (var n = 0; n < 4; ++n) {
setTimeout(test.bind(null, n, true), 200 * n);
setTimeout(test.bind(null, n, false), 200 * n + 100);
}
function test(num, gte) {
var truths = 0;
var alternativetruths = 0;
var errors = 0;
function game() {
var score = Math.floor(Math.random() * 10);
return gte ? score >= 5 : score > 5;
}
for (var i = 0; i < 999999; i++) {
var flag = game();
if (flag) {
truths++;
} else {
alternativetruths++;
}
}
showStats(num, gte, truths, alternativetruths);
}
function showStats(num, gte, truths, alternativetruths) {
var total = truths + alternativetruths; // Should be 999999 of course
var truthsPercent = (truths * 100) / total;
var altPercent = (alternativetruths * 100) / total;
console.log(num, gte ? ">=" : ">", "truths:", truths, "alternativetruths:", alternativetruths, "(" + truthsPercent.toFixed(2) + "% vs. " + altPercent.toFixed(2) + "%)");
}
.as-console-wrapper {
max-height: 100% !important;
}
You need to assign game to a var before test for its value. Otherwise, everytime yout check the value with game() you will check a new value. So it can be false at the first check and true at the second and for this reason increment your errors.
Try this:
for(i=0;i<999999;i++) {
let gameResult = game();
if (gameResult === true) {
truths++
} else if (gameResult === false) {
alternativetruths++
} else {
errors++
}
}

Returning factorials in JavaScript

I'm trying to create a script that returns the factorial of the input number as part of a challenge. When I try to run it, it returns the proper factorial, but apparently I did it wrong somehow.
It looks like this:
function FirstFactorial(num) {
if (num > 1) {
var x = num;
for (var i = 1; i < x; i++) {
num = num * i;
}
} else if (num === 1) {
return 1;
} else {
console.log("That's not a number!");
}
return num;
}
Then I tried doing it like this, but it still doesn't work!
function FirstFactorial(num) {
if (num < 0) {
num = 0;
console.log("You have to input a number!");
}
if (num === 0) {
return 1;
}
return num * FirstFactorial(num - 1);
}
The most likely reason is that they expected and intended you to use recursion (a function that calls itself).
If you think about factorials, each builds on the result of the previous one, which is the classic case for using recursion.
(Note that I'm specifically not posting code doing this with recursion, because presumably the point here is for you to work out how to do it.)

Categories

Resources