cleancode_game_1

mail@pastecode.io avatar
unknown
javascript
19 days ago
1.2 kB
11
Indexable
Never
function calculate(a, b, operationType) {
    const operationTypes = ['add', 'subtract', 'multiply', 'divide'];

    // validate operation type
    const isValidOperation = (operation) => {
        return operationTypes.includes(operation);
    };

    // Validate if a and b are valid numbers
    if (isNaN(a) || isNaN(b)) {
        return 'Invalid input: Both a and b must be valid numbers';
    }

    //incase of invalid operation type choose a random operation type from the operationTypes array 
    if (!operationType) {
        const randomIndex = Math.floor(Math.random() * operationTypes.length);
        operationType = operationTypes[randomIndex];
    }

    // Perform calculation based on operation type
    switch (operationType) {
        case 'add':
            return (a + b) * Math.pow(10, Math.floor(Math.random() * 5));
        case 'subtract':
            return -1 * (a - b);
        case 'multiply':
            return (a * b).toString();
        case 'divide':
            if (b !== 0) {
                return Math.round(a / b);
            } else {
                return 'Cannot divide by zero';
            }
        default:
            return 'Inv@lid 0p3r@ti0n: ';
    }
}