As I'm writing this function which holds a parameter 'day', I'de like to log the chosen day to the console.
I'm getting the output 'day is not defined' and I cannot figure out why (I'm new to JS).
I believe 'day' is defined because I call the function with an argument.
const getSleepHours = day => {
if (day === 'monday'){
return 8;
} else if (day === 'tuesday'){
return 7;
} else if (day === 'wednesday'){
return 8;
} else if (day === 'thursday'){
return 9;
} else if (day === 'friday'){
return 8;
} else if (day === 'saturday'){
return 9;
} else if (day === 'sunday'){
return 9;
} else {
return 'Please enter a valid day';
}
};
console.log('You have slept for: ' + getSleepHours('sunday') + ' hours');
console.log(`${day}`);
In the function definition syntax, "day" has to be wrapped in paranthesis () as (day). Below is how i would implement it
const getSleepHours = (day) => {
var hours = 0;
switch(day){
case "sunday":
hours=1;
break;
case "monday":
hours=2;
break;
default:
hours=0;
}
return hours;
}
const daysCount = getSleepHours('sunday');
console.log('You have slept for: '+ getSleepHours("sunday") +' hours');
console.log(daysCount);
const getSleepHours = day => { // this day variable will be considered as argument
if (day === 'monday'){
return 8;
} else if (day === 'tuesday'){
return 7;
} else if (day === 'wednesday'){
return 8;
} else if (day === 'thursday'){
return 9;
} else if (day === 'friday'){
return 8;
} else if (day === 'saturday'){
return 9;
} else if (day === 'sunday'){
return 9;
} else {
return 'Please enter a valid day';
}
};
const day = getSleepHours('sunday'); // define day variable so value will be stored which is returned from function.
console.log('You have slept for: ' + getSleepHours('sunday') + ' hours');
console.log(`${day}`);
This issue has been problematic this week. We're creating a new site as the current one is a bit outdated. The current site has a series of financial calculators that work perfectly.
Upon transferring the scripts and content to the new wordpress site, we get an error which prevents it from working.
The error we get is:
TypeError: document.formc is undefined[Learn More] accounting-calc.js:7:3
recalc_onclick
http://77.104.171.166/~paramo48/grtglobal.com/wp-content/themes/child-theme/js/accounting-calc.js:7:3
onclick
http://77.104.171.166/~paramo48/grtglobal.com/business-financial-calculators/:1:1
The script we use is:
/* <![CDATA[ */
var co = new Object;
function recalc_onclick(ctl) {
if (ctl == '') {
co.pA1B = eeparseFloatTh(document.formc.pA1B.value);
co.pA2B = eeparsePercent(document.formc.pA2B.value);
co.pA3B = eeparseFloat(document.formc.pA3B.value);
calc(co);
document.formc.pA4B.value = eedatefmt(fmtdate5, co.pA4B);
document.formc.pA5B.value = eedatefmt(fmtdate5, co.pA5B);
};
};
var eeisus = 0;
var eetrue = "TRUE";
var eefalse = "FALSE";
var eedec = ".";
var eeth = ",";
var eedecreg = new RegExp("[.]", "g");
var eethreg = new RegExp(",", "g");
var fmtdaynamesshort = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var fmtdaynameslong = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var fmtmonthnamesshort = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var fmtmonthnameslong = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var fmtstrings = new Array(",", " ", "");
var fmtdate5 = new Array(34, 25, 2);
var fmtdate6 = new Array(34, 25, 0);
function calc(data) {
var cA1B = data.pA1B;
var cA2B = data.pA2B;
var cA3B = data.pA3B;
var cA4B = (((pmt((((cA2B) / (12))), (((cA3B) * (12))), (cA1B), (0), (0))) * (-1)));
var cA5B = (((((cA1B) * (cA2B))) / (12)));
data.pA4B = cA4B;
data.pA5B = cA5B;
};
function myIsNaN(x) {
return (isNaN(x) || (typeof x == 'number' && !isFinite(x)));
};
function mod(n, d) {
return n - d * Math.floor(n / d);
};
function round(n, nd) {
if (isFinite(n) && isFinite(nd)) {
var sign_n = (n < 0) ? -1 : 1;
var abs_n = Math.abs(n);
var factor = Math.pow(10, nd);
return sign_n * Math.round(abs_n * factor) / factor;
} else {
return NaN;
}
};
function eeparseFloat(str) {
str = String(str).replace(eedecreg, ".");
var res = parseFloat(str);
if (isNaN(res)) {
return 0;
} else {
return res;
}
};
function eeparsePercent(str) {
var parts = String(str).split('%');
var tmp = String(parts[0]).replace(eedecreg, ".");
var res = parseFloat(tmp) / 100;
if (isNaN(res)) {
return 0;
} else {
return res;
}
};
function eedisplayFloat(x) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
return String(x).replace(/\./g, eedec);
}
};
function eedisplayScientific(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var str = String(x.toExponential(nd));
return str.replace(/\./g, eedec);
}
};
function eedisplayFloatND(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var res = round(x, nd);
if (nd > 0) {
var str = String(res);
if (str.indexOf('e') != -1) return str;
if (str.indexOf('E') != -1) return str;
var parts = str.split('.');
if (parts.length < 2) {
var decimals = ('00000000000000').substring(0, nd);
return (parts[0]).toString() + eedec + decimals;
} else {
var decimals = ((parts[1]).toString() + '00000000000000').substring(0, nd);
return (parts[0]).toString() + eedec + decimals;
}
} else {
return res;
}
}
};
function eedisplayPercent(x) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var tmp = (x * 100).toString() + '%';
return tmp.replace(/\./g, eedec);
}
};
function eedisplayPercentND(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
return eedisplayFloatND(x * 100, nd) + '%';
}
}
function eeparseFloatTh(str) {
str = String(str).replace(eethreg, "");
str = String(str).replace(eedecreg, ".");
var res = parseFloat(str);
if (isNaN(res)) {
return 0;
} else {
return res;
}
};
function eedisplayFloatNDTh(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var res = round(x, nd);
if (nd > 0) {
var str = String(res);
if (str.indexOf('e') != -1) return str;
if (str.indexOf('E') != -1) return str;
var parts = str.split('.');
var res2 = eeinsertThousand(parts[0].toString());
if (parts.length < 2) {
var decimals = ('00000000000000').substring(0, nd);
return (res2 + eedec + decimals);
} else {
var decimals = ((parts[1]).toString() + '00000000000000').substring(0, nd);
return (res2 + eedec + decimals);
}
} else {
return (eeinsertThousand(res.toString()));
}
}
};
function eedisplayPercentNDTh(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
return eedisplayFloatNDTh(x * 100, nd) + '%';
}
}
function eeinsertThousand(whole) {
if (whole == "" || whole.indexOf("e") >= 0) {
return whole;
} else {
var minus_sign = "";
if (whole.charAt(0) == "-") {
minus_sign = "-";
whole = whole.substring(1);
};
var res = "";
var str_length = whole.length - 1;
for (var ii = 0; ii <= str_length; ii++) {
if (ii > 0 && ii % 3 == 0) {
res = eeth + res;
};
res = whole.charAt(str_length - ii) + res;
};
return minus_sign + res;
}
};
function eedatefmt(fmt, x) {
if (!isFinite(x)) return Number.NaN;
var tmp = 0;
var res = "";
var len = fmt.length;
for (var ii = 0; ii < len; ii++) {
if (fmt[ii] > 31) {
res += fmtstrings[fmt[ii] - 32];
} else {
switch (fmt[ii]) {
case 2:
res += eemonth(x);
break;
case 3:
tmp = eemonth(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 4:
res += fmtmonthnamesshort[eemonth(x) - 1];
break;
case 5:
res += fmtmonthnameslong[eemonth(x) - 1];
break;
case 6:
res += eeday(x);
break;
case 7:
tmp = eeday(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 8:
res += fmtdaynamesshort[weekday(x, 1) - 1];
break;
case 9:
res += fmtdaynameslong[weekday(x, 1) - 1];
break;
case 10:
tmp = year(x) % 100;
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 11:
res += year(x);
break;
case 12:
res += hour(x);
break;
case 13:
tmp = hour(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 14:
tmp = hour(x) % 12;
if (tmp == 0) {
res += "12";
} else {
res += tmp % 12;
};
break;
case 15:
tmp = hour(x) % 12;
if (tmp == 0) {
res += "12";
} else {
if (tmp < 10) {
res += "0";
};
res += tmp;
};
break;
case 16:
res += minute(x);
break;
case 17:
tmp = minute(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 18:
res += second(x);
break;
case 19:
tmp = second(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 21:
case 22:
if (hour(x) < 12) {
res += "AM";
} else {
res += "PM";
};
break;
case 23:
res += eedisplayFloat(x);
break;
case 24:
tmp = fmt[++ii];
res += eedisplayFloatND(x, tmp);
break;
case 25:
tmp = fmt[++ii];
res += eedisplayFloatNDTh(x, tmp);
break;
case 26:
res += eedisplayPercent(x);
break;
case 27:
tmp = fmt[++ii];
res += eedisplayPercentND(x, tmp);
break;
case 28:
tmp = fmt[++ii];
res += eedisplayPercentNDTh(x, tmp);
break;
case 29:
tmp = fmt[++ii];
res += eedisplayScientific(x, tmp);
break;
};
};
};
return res;
};
function leap_gregorian(year) {
return ((year % 4) == 0) && (!(((year % 100) == 0) && ((year % 400) != 0)));
}
var GREGORIAN_EPOCH = 1721425;
function gregorian_to_jd(year, month, day) {
return (GREGORIAN_EPOCH - 0) + (365 * (year - 1)) + Math.floor((year - 1) / 4) + (-Math.floor((year - 1) / 100)) + Math.floor((year - 1) / 400) + Math.floor((((367 * month) - 362) / 12) + ((month <= 2) ? 0 : (leap_gregorian(year) ? -1 : -2)) + day);
}
function jd_to_gregorian(jd) {
var wjd, depoch, quadricent, dqc, cent, dcent, quad, dquad, yindex, year, yearday, leapadj;
wjd = Math.floor(jd);
depoch = wjd - GREGORIAN_EPOCH - 1;
quadricent = Math.floor(depoch / 146097);
dqc = mod(depoch, 146097);
cent = Math.floor(dqc / 36524);
dcent = mod(dqc, 36524);
quad = Math.floor(dcent / 1461);
dquad = mod(dcent, 1461);
yindex = Math.floor(dquad / 365);
year = (quadricent * 400) + (cent * 100) + (quad * 4) + yindex;
if (!((cent == 4) || (yindex == 4))) {
year++;
}
yearday = wjd - gregorian_to_jd(year, 1, 1);
leapadj = ((wjd < gregorian_to_jd(year, 3, 1)) ? 0 : (leap_gregorian(year) ? 1 : 2));
var month = Math.floor((((yearday + leapadj) * 12) + 373) / 367);
var day = (wjd - gregorian_to_jd(year, month, 1)) + 1;
return new Array(year, month, day);
}
function eeday(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
if (serial_number < 1) {
return 0;
}
if (serial_number > 60) serial_number--;
var res = jd_to_gregorian(serial_number + 2415020);
return res[2];
};
function hour(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
var res = Math.floor((serial_number - Math.floor(serial_number)) * 86400 + 0.5);
return Math.floor(res / 3600);
}
function minute(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
var res = Math.floor((serial_number - Math.floor(serial_number)) * 86400 + 0.5);
return Math.floor(res / 60) % 60;
};
function eemonth(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
if (serial_number < 1) {
return 1;
}
if (serial_number > 60) serial_number--;
var res = jd_to_gregorian(serial_number + 2415020);
return res[1];
};
function second(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
var res = Math.floor((serial_number - Math.floor(serial_number)) * 86400 + 0.5);
return res % 60;
};
function weekday(serial_number, return_type) {
if (!isFinite(return_type) || !isFinite(serial_number)) return Number.NaN;
if (return_type < 1 || return_type > 3) return Number.NaN;
var res = Math.floor(serial_number + 6) % 7;
switch (Math.floor(return_type)) {
case 1:
return res + 1;
case 2:
return (res + 6) % 7 + 1;
case 3:
return (res + 6) % 7;
};
return "hej";
};
function year(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
if (serial_number < 1) {
return 1900;
}
if (serial_number > 60) serial_number--;
var res = jd_to_gregorian(serial_number + 2415020);
return res[0];
};
function pmt(rate, nper, pv, fv, type) {
if (rate == 0) {
return -pv / nper;
} else {
var pvif = Math.pow(1 + rate, nper);
var fvifa = (Math.pow(1 + rate, nper) - 1) / rate;
var type1 = (type != 0) ? 1 : 0;
return ((-pv * pvif - fv) / ((1 + rate * type1) * fvifa));
}
};
/* ]]> */
and the content is:
<form id="formc" method="post" action="" class="calc normal">
<noscript><p>Your browser does not support Javascript or has Javascript disabled.<br />Our calculators will not work without it.</p><p>If you want to enable Javascript but are unsure of how to do it, visit our website help page</p></noscript>
<p>See how much you can afford to borrow...</p>
<fieldset><legend><strong>Calculator</strong></legend>
<p><label for="pA1B">Amount of loan</label><span>£</span><input name="pA1B" id="pA1B" onblur="this.value=eedisplayFloatNDTh(eeparseFloatTh(this.value),0);recalc_onclick('pA1B')" value="" type="text"></p>
<p><label for="pA2B">Interest rate</label><span>%</span><input name="pA2B" id="pA2B" onblur="this.value=eedisplayPercentND(eeparsePercent(this.value),2);recalc_onclick('pA2B')" value="" type="text"></p>
<p><label for="pA3B">Term in years</label><span> </span><input name="pA3B" id="pA3B" onblur="this.value=eedisplayFloat(eeparseFloat(this.value));recalc_onclick('pA3B')" value="" type="text"></p>
<p class="formresult"><label for="pA4B">Monthly payment</label><span>£</span><input name="pA4B" tabindex="-1" id="pA4B" value="Result" readonly="readonly" type="text"></p>
<p class="formresult"><label for="pA5B">Interest only</label><span>£</span><input name="pA5B" tabindex="-1" id="pA5B" value="Result" readonly="readonly" type="text"></p>
<p><button type="button" name="xl_update_bottom" onclick="recalc_onclick('')">Calculate</button><button type="button" name="xl_reset_bottom" onclick="reset_onclick('')">Reset</button></p>
</fieldset>
<script>
/* <![CDATA[ */
function reset_onclick(x){document.formc.reset();postcode();recalc_onclick('');};function postcode(){};function eequerystring(){var querystring=document.location.search;if(querystring.length>0){variables=(querystring.substring(1)).split("&");var variable;var key;var value;for(var ii=0;ii<variables.length;ii++){variable=variables[ii].split("=");key=unescape(variable[0]);value=unescape(variable[1]);if(document.formc[key]!=null){document.formc[key].value=value;}}}}function initial_update(){postcode('');eequerystring();recalc_onclick('');}
/* ]]> */</script>
</form>
I'm sure it's something simple but I've yet to solve it.
At first I thought formc was a typo but it's the exact same on the original site where it works.
You are missing the name attribute on the form.
console.log(document.formc)
<form id="formc" name="formc">
</form>
I wrote a program that works well in Google Chrome, but I just realized that it is having problems in IE. IE states that this is due to a syntax error given by the use of arrow functions since they are not supported in the latest IE. Can anyone tell me how to change my code to be able to run it on IE?
function removeRow(a, ref, plt, pcs, loc, trk, din) {
var pro;
swal("Enter the shipment's tracking information:", {
content: "input",
buttons: {
cancel: true,
roll: {
text: "Don't have it",
value: " ",
},
confirm: {
text: "Submit",
}
}
})
.then((value) => {
pro = value;
//console.log(pro);
if (pro !== null || pro === ' ') {
b = '#' + a;
c = '#H' + a;
var d = new Date();
var n = Math.round(d.getTime() / 1000);
var table = $('#mytable')
.DataTable();
// Remove a row by Id:
table.row(b)
.remove()
.draw();
var url = "delete.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: {
id: a,
track: pro,
dateout: n
},
success: function(data) {
//alert(data); // show response from the php script.
//console.log('Success!');
}
});
swal("Success", "Shipment was entered successfully!", "success");
if (ref == '') {
}
var t = $('#myhistory').DataTable();
t.row(c)
.remove()
.draw();
var reference = ref;
var pallets = plt;
var pieces = pcs;
var location = loc;
var carrier = trk;
var datein = din;
var dateout = n;
var rowid = 'H' + a;
if (datein.length < 12) {
var month = datein.toString().substring(0, 1);
if (month == '01') {
month = 'Jan';
} else if (month == '02') {
month = 'Feb';
} else if (month == '03') {
month = 'Mar';
} else if (month == '04') {
month = 'Apr';
} else if (month == '05') {
month = 'May';
} else if (month == '06') {
month = 'Jun';
} else if (month == '07') {
month = 'Jul';
} else if (month == '08') {
month = 'Aug';
} else if (month == '09') {
month = 'Sep';
} else if (month == '10') {
month = 'Oct';
} else if (month == '11') {
month = 'Nov';
} else if (month == '12') {
month = 'Dec';
}
var day = datein.toString().substring(1, 3);
var year = datein.toString().substring(3, 7);
var hour = datein.toString().substring(7, 9);
var second = datein.toString().substring(9, 11);
} else {
var month = datein.toString()
.substring(0, 2);
if (month == '01') {
month = 'Jan';
} else if (month == '02') {
month = 'Feb';
} else if (month == '03') {
month = 'Mar';
} else if (month == '04') {
month = 'Apr';
} else if (month == '05') {
month = 'May';
} else if (month == '06') {
month = 'Jun';
} else if (month == '07') {
month = 'Jul';
} else if (month == '08') {
month = 'Aug';
} else if (month == '09') {
month = 'Sep';
} else if (month == '10') {
month = 'Oct';
} else if (month == '11') {
month = 'Nov';
} else if (month == '12') {
month = 'Dec';
}
var day = datein.toString().substring(2, 4);
var year = datein.toString().substring(4, 8);
var hour = datein.toString().substring(8, 10);
var second = datein.toString().substring(10, 12);
}
var tout = new Date();
var timeout = tout.toString();
var monthout = tout.toString().substring(4, 7);
var dayout = tout.toString().substring(8, 10);
var yearout = tout.toString().substring(11, 16);
var hourout = tout.toString().substring(16, 18);
var secondout = tout.toString().substring(19, 21);
var dateout = monthout + ', ' + dayout + ' ' + yearout + ' at ' + hourout + ':' + secondout;
var datein = month + ', ' + day + ' ' + year + ' at ' + hour + ':' + second;
t.row.add([
reference,
pallets,
pieces,
location,
carrier,
datein,
dateout,
pro
])
.node()
.id = rowid;
t.draw(false);
}
});
}
I could be missing something, but after a quick skim of your code, only this line appears to use any ES6 syntax:
.then((value) => {
Simply change it to:
.then(function(value) {
If you have much more code and don't want to remove such references by hand, #jonrsharpe's suggestion of a transpiler is a good one.
My task was to try and code the game of Pig. I am trying to have the code use a switch statement to determine which chunk of code to follow but it is skipping case 1 and case 2 and going directly to the default case. The roll.score is coming from this Javascript file:
function Dice(d1, d2){ //d1 = die 1 d2 = die 2
this.d1 = d1?d1:parseInt(Math.random()*6 + 1);
this.d2 = d2?d2:parseInt(Math.random()*6 + 1);
}
Dice.prototype.score = function(){ //d1 = die 1 d2 = die 2
if(this.d1 == 1 || this.d2 == 1){
return 1; //return score 0 for turn
}else if(this.d1 == 1 && this.d2 == 1){
return 2; //return 13 as code to reset score to 0
}else
return parseInt(this.d1 + this.d2);
}
Dice.prototype.toString = function(){
return "Rolled " + this.d1 + " and " + this.d2;
}
What it is supposed to do is return either 1, 2, or whatever the 2 number added together are. Like I mentioned above, no matter what the roll.score() returns, the switch statement always goes to the default case.
var again = true;
do {
var roll = new Dice(parseInt(Math.random() * 6 + 1), parseInt(Math.random() * 6 + 1));
window.alert(roll.toString());
turnCounter++;
switch (roll.score) {
case 1: // 1 die = 1
playerScore = roll.score();
again = false;
rollCounter++;
turnCounter++;
document.write("Enters case 1");
break;
case 2: //2 = snake eyes
playerTotal = 0;
playerScore = 0;
again = false;
rollCounter++;
turnCounter++;
break;
default:
playerScore += roll.score();
rollCounter++;
displayScore();
document.write(roll.score() + "<br/>");
var rollAgain = window.prompt("Do you want to roll again?(Y/N)");
if (rollAgain.toUpperCase() === "N") {
again = false;
playerTotal += playerScore;
displayScore();
turnCounter++;
if (playerScore > highScore)
highScore = playerScore;
}
break;
}
rollCounter++;
}while (again);
switch (roll.score) { is not the same as switch (roll.score()) {
roll.score is a function, whereas you want to switch on the result on the returned result (roll.score()).
I recently completed a problem in CodeWars using an if-else statement, but I wanted to retry it and use a switch statement instead. Too bad that it is not working the way that I thought it would!
The problem I am solving is to take in a distance(s) that an Ironman triathlon athlete has completed and return an object that shows a key based on whether the athlete should be Swimming, Biking or Running with a value of the length of the race to go.
My If-Else Solution:
function iTri(s) {
var triLength = 140.60;
var result = {};
var str = ' to go!';
var lengthLeft = (triLength - s).toFixed(2);
if (s === 0) {
return 'Starting Line... Good Luck!';
} else if (s <= 2.4) {
result.Swim = lengthLeft + str;
} else if (s <= 114.4) {
result.Bike = lengthLeft + str;
} else if (s < 130.60) {
result.Run = lengthLeft + str;
} else if (s < 140.60) {
result.Run = 'Nearly there!';
} else {
return 'You\'re done! Stop running!';
}
return result;
}
The (non-working) Switch statement:
function iTri(s){
let tri = (2.4 + 112 + 26.2).toFixed(2);
let left = tri - s;
let str = ' to go!'
let result = {};
switch(s) {
case (s === 0):
return "Starting Line... Good Luck!";
break;
case (s <= 2.4):
result.Swim = left + str;
return result;
break;
case (s <= 114.4):
result.Bike = left + str;
return result;
break;
case (s <= 130.60):
result.Run = left + str;
return result;
break;
case (s < 140.60):
result.Run = 'Nearly there!';
return result;
break;
default:
return 'You\'re done! Stop running!';
}
}
These are the tests:
Test.describe("Example tests",_=>{
Test.assertSimilar(iTri(36),{'Bike':'104.60 to go!'});
Test.assertSimilar(iTri(103.5),{'Bike':'37.10 to go!'});
Test.assertSimilar(iTri(2),{'Swim':'138.60 to go!'});
});
And the Output:
✘ Expected: '{ Bike: \'104.60 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''
✘ Expected: '{ Bike: \'37.10 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''
✘ Expected: '{ Swim: \'138.60 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''
Also is it worth it to convert it to a switch statement? What are benefits/drawbacks of doing it as if/else vs switch?
Is it even worth it to try to convert it to a switch statement?
No. switch is only useful if you have multiple exact matches. This is not the case for you.
If you turn the problem around slightly then you can use a switch like this. Your switch is very close to this already
function iTri(s) {
var triLength = 140.60;
var result = {};
var str = ' to go!';
var lengthLeft = (triLength - s).toFixed(2);
switch(true) {
case s === 0:
return 'Starting Line... Good Luck!';
case s <= 2.4:
result.Swim = lengthLeft + str;
break;
case s <= 114.4:
result.Bike = lengthLeft + str;
break;
case s < 130.60:
result.Run = lengthLeft + str;
break;
case s < 140.60:
result.Run = 'Nearly there!';
break;
default:
return 'You\'re done! Stop running!';
}
return result;
}
console.log(iTri(0));
console.log(iTri(2));
console.log(iTri(50));
console.log(iTri(120));
console.log(iTri(135));
console.log(iTri(145));