How to calculate the area, diameter, and circumference of a circle in Node.js

2 Answers

0 votes
const radius = 3;
const PI = Math.PI;
    
const area = PI * radius * radius;
console.log("Area = " +  area.toFixed(2));
    
const diameter = 2 * radius;
console.log("Diameter = " +  diameter.toFixed(2));
    
const circumference = 2 * PI * radius;
console.log("Circumference = " +  circumference.toFixed(2));
 
     
     
/*
run:
       
Area = 28.27
Diameter = 6.00
Circumference = 18.85
       
*/

 



answered Aug 29, 2024 by avibootz
edited Aug 29, 2024 by avibootz
0 votes
/**
 * 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

*/

 



answered 2 hours ago by avibootz

Related questions

...