Generally breaking code to small intuitively named chunks pays off in readability, maintainability and, partially, in the size of "functional part" of the code. While accepted answer demonstrates it well: it extracts core functionality to a single procedure of two function calls, for the sake of exercise, let's break the code even further, add some type definitions and check some format.
While question lacks the final step ("what is the intended product of the code") let's say we want to display each "truck fase" (probably 'track lap') times in respective colour in HTML. As seen, while the core functionality shrunk into lapDisplay(lapTitle, data) (lapDisplay function being also quite terse), sum of all utility functions grew in size considerably:
//@ts-check
"use strict";
/*
§ "The data"
*/
/**
* @type {lapRecords}
*/
var laps = {
"Phase 1": {
"time": '00:15:15',
},
"Phase 2": {
"time": '00:19:30',
},
"Phase 3": {
"time": '00:30:23',
}
};
/*
§ "Functionality"
*/
for (const lapTitle in laps) {
const data = laps[lapTitle];
const outHTML = lapDisplay(lapTitle, data);
document.body.insertAdjacentHTML('beforeend', outHTML);
};
/*
§ "Utility Functions"
*/
/**
* @param {string} title
* @param {lapRecord} data
*/
function lapDisplay (title, data) {
const duration = data.time;
const inMinutes = durationStringToMinutes(duration);
const colour = minutesToColour(inMinutes)
return `<p style="color: ${colour}">
"${title}" took ${duration}
<small>(${inMinutes.toFixed(2)} minutes)</small>.</p>
`;
};
/**
* @param {number} minutes
* @return {string} hex colour
* @todo get ranges-colour mapping from config object
*/
function minutesToColour (minutes) {
if (minutes <= 18) {
return "#0CC234";
}
if (minutes < 30) {
return "#FACE5A";
}
return "#FF0101";
};
/**
* @param {HoursMinutesSecondsDuration} hoursMinutesSeconds separated with colons
*/
function durationStringToMinutes (hoursMinutesSeconds) {
if (/^[0-9]+:[0-9]+:[0-9]+$/.test(hoursMinutesSeconds) === false) {
throw Error(`${hoursMinutesSeconds} is in wrong format.`)
}
let [hours,
minutes,
seconds] = hoursMinutesSeconds.split(":").map(_ => parseInt(_, 10));
minutes += hours * 60;
minutes += seconds / 60;
return minutes
};
/*
§ Type definitions
*/
/**
* @typedef {`${number}:${number}:${number}`} HoursMinutesSecondsDuration
* @typedef {{"time":HoursMinutesSecondsDuration}} lapRecord
* @typedef {Object<string,lapRecord>} lapRecords
*/