JSFiddle - React, Tailwind, and code Playground
by Terrance Smith
HTML
<div id="powermsg">Hi</div>
<a href="#" onclick="changePowerMsg(200);">Change!</a>
JavaScript
function getPowerMsg(kj) {
var kwh = kj * 0.00027777777777778;
var results = [];
var stuff = [
["an LED night light", 0.5],
["a clock radio", 4],
["a night light", 5]
];
for (var i = 0; i < stuff.length; i++) {
item = stuff[i][0];
watts = stuff[i][1];
kwatts = watts / 1000;
hours = (Math.floor((kwh / kwatts) * 2) / 2);
if (hours > 0) {
results.push([item, convertTime(hours)]);
}
}
return results[randbetween(0, results.length - 1)];
}
function convertTime(hrs) {
var msg = "";
if (hrs < 24) {
msg = hrs + " hour";
if (hrs != 1) {
msg += "s";
}
if (hrs < 1) {
msg = "a half hour";
}
} else if (hrs == 24) {
msg = "a full day";
} else if (hrs < 33) {
msg = "over a day";
} else if (hrs < 39) {
msg = "about a day and a half";
} else if (hrs < 48) {
msg = "almost 2 days";
} else if (hrs == 48) {
msg = "2 days";
} else if (hrs < 60) {
msg = "over 2 days";
} else if (hrs < 72) {
msg = "almost 3 days";
} else if (hrs == 72) {
msg = "3 days";
} else {
msg = "over 3 days";
}
return msg;
}
function changePowerMsg(num) {
document.getElementById("powermsg").innerHTML = getPowerMsg(num);
}