When building utility tools for the web, the most critical aspect isn't the UI—it’s the precision of the logic. Whether you’re calculating currency, time, or cooking safety metrics, your application must rely on a set of "Source of Truth" constants that handle edge cases seamlessly.
Today, we’re looking at how to structure a utility that manages cooking safety data.
Structuring Utility Logic
Instead of mixing logic with view state, it's best practice to separate your safety calculations into a dedicated utility file. This makes your logic unit-testable.
// constants.js
export const COOKING_CONSTANTS = {
THAW_HOURS_PER_LB: 5,
ROAST_MINS_UNSTUFFED: 15,
ROAST_MINS_STUFFED: 18,
};
// logic.js
import { COOKING_CONSTANTS } from './constants.js';
export const getPreparationTimeline = (weight, isStuffed) => {
if (weight <= 0) throw new Error("Weight must be greater than zero.");
const roastMins = isStuffed
? COOKING_CONSTANTS.ROAST_MINS_STUFFED
: COOKING_CONSTANTS.ROAST_MINS_UNSTUFFED;
return {
thawDays: (weight * COOKING_CONSTANTS.THAW_HOURS_PER_LB) / 24,
roastMinutes: weight * roastMins,
};
};
Why This Approach?
-
Maintainability: By abstracting
COOKING_CONSTANTS, you can update safety guidelines (e.g., changing time-per-pound values) in one place without breaking your front-end components. - Predictability: Utilizing a single entry point for calculations prevents floating-point drift and logic branching across your application.
-
Safety First: Note the error handling for
weight <= 0. In utility tools, defensive programming is your first line of defense against providing dangerous advice to a user.
For those interested in seeing this architecture applied to a real-world, mobile-friendly project, you can examine the production-ready implementation of these constants in the Turkey Roasting & Refrigerator Thaw Calculator. It’s an excellent example of how clean, modular JavaScript translates into a highly useful, low-latency browser tool.
Top comments (0)