Adding to the already provided answers, a major style issue in your code is the excessive repetition that can be eliminated by utilizing loops and functions.
Furthermore, the mathematical calculations could be simplified significantly, rendering the need to search for 'E' or '.' unnecessary. Considering this, using a loop may not be necessary; in the example below, a loop is only employed to add labels. It's advisable to use descriptive variable names (hours
, minutes
instead of a
, b
) whenever possible to enhance code readability.
Visit this link for reference.
function calculateTime(seconds) {
if (seconds === '') {
seconds = 54098;
} // Time value converted to seconds
seconds = Math.floor(seconds);
if (isNaN(seconds) || seconds <= 0) {
return '<i>No time specified</i>';
}
var minutes = Math.floor(seconds / 60),
hours = Math.floor(minutes / 60),
days = Math.floor(hours / 24),
years = Math.floor(days / 365), // assuming non-leap year!
timeData = [years, days % 365, hours % 24, minutes % 60, seconds % 60],
pluralLabels = ['years', 'days', 'hours', 'minutes' , 'seconds'],
singularLabels = ['year', 'day', 'hour', 'minute', 'second'],
time = [];
for (var i = 0; i < timeData.length; i++) {
if (timeData[i] > 1) {
time.push(timeData[i] + ' ' + pluralLabels[i]);
}
else if (timeData[i] > 0) {
time.push(timeData[i] + ' ' + singularLabels[i]);
}
}
var lastEntry = time.pop();
return time.length ? time.join(', ') + ' and ' + lastEntry : lastEntry;
}
document.getElementById("result").innerHTML = calculateTime(83200);
Check out this alternative method which utilizes loops more efficiently for mathematical computations.