/**
* Calculates the diameter, circumference, and area of a circle.
*
* @param {number} radius - The radius of the circle (must be a non-negative number).
* @returns {Object} An object containing the diameter, circumference, and area.
* @throws {TypeError} If the radius is not a valid number.
* @throws {RangeError} If the radius is negative.
*/
export function calculateCircleMetrics(radius) {
// Validate input type and ensure it's not NaN
if (typeof radius !== 'number' || Number.isNaN(radius)) {
throw new TypeError('Radius must be a valid number.');
}
// Guard clause: geometric radius cannot be negative
if (radius < 0) {
throw new RangeError('Radius cannot be negative.');
}
const diameter = 2.0 * radius;
const circumference = 2.0 * Math.PI * radius;
// Standard multiplication (radius * radius) is more efficient than Math.pow(radius, 2)
const area = Math.PI * (radius * radius);
return {
diameter,
circumference,
area
};
}
// --- Example Execution ---
if (process.argv[1] === import.meta.filename) {
try {
const radius = 3.0;
// Retrieve calculated metrics using object destructuring
const { diameter, circumference, area } = calculateCircleMetrics(radius);
// Output results formatted to 2 decimal places using toFixed()
console.log(`Radius: ${radius}`);
console.log(`Diameter: ${diameter}`);
console.log(`Circumference: ${circumference.toFixed(2)}`);
console.log(`Area: ${area.toFixed(2)}`);
}
catch (error) {
console.error(`Error: ${error.message}`);
process.exitCode = 1;
}
}
/*
run:
Radius: 3
Diameter: 6
Circumference: 18.85
Area: 28.27
*/