calculator.js•3.35 kB
class Calculator {
constructor() {
this.operations = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => {
if (b === 0) throw new Error('Division by zero is not allowed');
return a / b;
},
power: (a, b) => Math.pow(a, b),
sqrt: (a) => {
if (a < 0) throw new Error('Cannot calculate square root of negative number');
return Math.sqrt(a);
},
sin: (a) => Math.sin(a),
cos: (a) => Math.cos(a),
tan: (a) => Math.tan(a),
log: (a) => {
if (a <= 0) throw new Error('Cannot calculate logarithm of non-positive number');
return Math.log(a);
},
abs: (a) => Math.abs(a),
round: (a) => Math.round(a),
floor: (a) => Math.floor(a),
ceil: (a) => Math.ceil(a)
};
}
calculate(operation, ...args) {
if (!this.operations[operation]) {
throw new Error(`Unknown operation: ${operation}`);
}
// Convert string numbers to actual numbers
const numericArgs = args.map(arg => {
const num = parseFloat(arg);
if (isNaN(num)) {
throw new Error(`Invalid number: ${arg}`);
}
return num;
});
try {
const result = this.operations[operation](...numericArgs);
return {
operation,
args: numericArgs,
result,
timestamp: new Date().toISOString()
};
} catch (error) {
throw new Error(`Calculation error: ${error.message}`);
}
}
getAvailableOperations() {
return [
'add', 'subtract', 'multiply', 'divide',
'power', 'sqrt', 'sin', 'cos', 'tan',
'log', 'abs', 'round', 'floor', 'ceil'
];
}
// Complex calculations
calculateExpression(expression) {
try {
// Basic expression evaluation (be careful with eval in production)
const sanitizedExpression = expression.replace(/[^0-9+\-*/().,]/g, '');
const result = eval(sanitizedExpression);
if (isNaN(result) || !isFinite(result)) {
throw new Error('Invalid expression result');
}
return {
expression: sanitizedExpression,
result,
timestamp: new Date().toISOString()
};
} catch (error) {
throw new Error(`Expression evaluation error: ${error.message}`);
}
}
// Statistical functions
calculateStats(numbers) {
const numericArray = numbers.map(n => parseFloat(n)).filter(n => !isNaN(n));
if (numericArray.length === 0) {
throw new Error('No valid numbers provided');
}
const sum = numericArray.reduce((a, b) => a + b, 0);
const mean = sum / numericArray.length;
const sorted = numericArray.sort((a, b) => a - b);
const median = sorted.length % 2 === 0
? (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]) / 2
: sorted[Math.floor(sorted.length / 2)];
const variance = numericArray.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / numericArray.length;
const stdDev = Math.sqrt(variance);
return {
numbers: numericArray,
count: numericArray.length,
sum,
mean,
median,
variance,
stdDev,
min: Math.min(...numericArray),
max: Math.max(...numericArray),
timestamp: new Date().toISOString()
};
}
}
export default Calculator;