-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
859 lines (729 loc) · 33.7 KB
/
script.js
File metadata and controls
859 lines (729 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
document.addEventListener('DOMContentLoaded', function() {
// DOM Elements
const themeToggle = document.getElementById('themeToggle');
const body = document.body;
const tabPanes = document.querySelectorAll('.tab-pane');
const tabBtns = document.querySelectorAll('.tab-btn');
const historyList = document.getElementById('historyList');
const clearHistoryBtn = document.getElementById('clearHistoryBtn');
// Theme Toggle
themeToggle.addEventListener('click', toggleTheme);
function toggleTheme() {
body.classList.toggle('light');
body.classList.toggle('dark');
if (body.classList.contains('dark')) {
themeToggle.innerHTML = '<i class="fas fa-sun"></i> Light Mode';
} else {
themeToggle.innerHTML = '<i class="fas fa-moon"></i> Dark Mode';
}
}
// Tab Switching
tabBtns.forEach(btn => {
btn.addEventListener('click', () => {
const tabId = btn.getAttribute('data-tab');
// Update active tab button
tabBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
// Show corresponding tab pane
tabPanes.forEach(pane => pane.classList.remove('active'));
document.getElementById(tabId).classList.add('active');
});
});
// Initialize Standard Calculator
initStandardCalculator();
// Initialize Scientific Calculator
initScientificCalculator();
// Initialize Unit Converter
initUnitConverter();
// Initialize Currency Converter
initCurrencyConverter();
// Initialize Age Calculator
initAgeCalculator();
// Initialize Formula Solver
initFormulaSolver();
// History Functions
clearHistoryBtn.addEventListener('click', clearHistory);
function addToHistory(entry) {
const li = document.createElement('li');
li.className = 'history-item';
li.textContent = entry;
// Add click event to reuse calculation
li.addEventListener('click', function() {
// Extract the result from history entry
const result = entry.split('=')[1].trim();
// Set the current value in the active calculator
const activePane = document.querySelector('.tab-pane.active');
if (activePane.id === 'standard') {
document.querySelector('.standard-calculator .current-value').textContent = result;
} else if (activePane.id === 'scientific') {
document.querySelector('.scientific-calculator .display').textContent = result;
}
});
historyList.prepend(li);
// Limit history to 50 items
if (historyList.children.length > 50) {
historyList.removeChild(historyList.lastChild);
}
}
function clearHistory() {
historyList.innerHTML = '<li class="empty-history">No history yet</li>';
}
// Standard Calculator Functions
function initStandardCalculator() {
const displayCurrent = document.querySelector('.standard-calculator .current-value');
const displayPrevious = document.querySelector('.standard-calculator .previous-value');
const buttons = document.querySelectorAll('.standard-calculator button:not(.operator)');
const operatorButtons = document.querySelectorAll('.standard-calculator .operator');
let currentValue = '0';
let previousValue = '';
let operation = null;
let resetScreen = false;
// Number buttons
buttons.forEach(button => {
button.addEventListener('click', () => {
const value = button.textContent;
if (value === 'AC') {
clearAll();
} else if (value === '+/-') {
toggleSign();
} else if (value === '%') {
percentage();
} else if (value === '.') {
addDecimal();
} else if (value === '0' && currentValue === '0') {
return;
} else if (currentValue === '0' || resetScreen) {
currentValue = value;
resetScreen = false;
} else {
currentValue += value;
}
displayCurrent.textContent = currentValue;
});
});
// Operator buttons
operatorButtons.forEach(button => {
button.addEventListener('click', () => {
const op = button.textContent;
if (op === '=') {
calculate();
} else if (op === 'x^y') {
setOperation('^');
} else {
setOperation(op);
}
});
});
function clearAll() {
currentValue = '0';
previousValue = '';
operation = null;
displayCurrent.textContent = currentValue;
displayPrevious.textContent = '';
}
function toggleSign() {
currentValue = (parseFloat(currentValue) * -1).toString();
displayCurrent.textContent = currentValue;
}
function percentage() {
currentValue = (parseFloat(currentValue) / 100).toString();
displayCurrent.textContent = currentValue;
}
function addDecimal() {
if (resetScreen) {
currentValue = '0.';
resetScreen = false;
return;
}
if (!currentValue.includes('.')) {
currentValue += '.';
}
}
function setOperation(op) {
if (operation && previousValue) {
calculate();
}
operation = op;
previousValue = currentValue;
displayPrevious.textContent = `${previousValue} ${operation}`;
resetScreen = true;
}
function calculate() {
if (!operation || previousValue === '') return;
let result;
try {
result = evaluate(parseFloat(previousValue), parseFloat(currentValue), operation);
addToHistory(`${previousValue} ${operation} ${currentValue} = ${result}`);
currentValue = result.toString();
displayCurrent.textContent = currentValue;
displayPrevious.textContent = '';
operation = null;
resetScreen = true;
} catch (error) {
currentValue = 'Error';
displayCurrent.textContent = currentValue;
previousValue = '';
operation = null;
}
}
function evaluate(a, b, op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '×': return a * b;
case '÷':
if (b === 0) throw new Error('Division by zero');
return a / b;
case '^': return Math.pow(a, b);
default: throw new Error('Unknown operation');
}
}
}
// Scientific Calculator Functions
function initScientificCalculator() {
const display = document.querySelector('.scientific-calculator .display');
const buttons = document.querySelectorAll('.scientific-calculator button');
let currentValue = '0';
buttons.forEach(button => {
button.addEventListener('click', () => {
const func = button.textContent;
try {
let result;
switch (func) {
case '√':
result = Math.sqrt(parseFloat(currentValue));
addToHistory(`√(${currentValue}) = ${result}`);
break;
case 'x²':
result = Math.pow(parseFloat(currentValue), 2);
addToHistory(`(${currentValue})² = ${result}`);
break;
case 'x³':
result = Math.pow(parseFloat(currentValue), 3);
addToHistory(`(${currentValue})³ = ${result}`);
break;
case 'log':
result = Math.log10(parseFloat(currentValue));
addToHistory(`log(${currentValue}) = ${result}`);
break;
case 'ln':
result = Math.log(parseFloat(currentValue));
addToHistory(`ln(${currentValue}) = ${result}`);
break;
case 'sin':
result = Math.sin(parseFloat(currentValue));
addToHistory(`sin(${currentValue}) = ${result}`);
break;
case 'cos':
result = Math.cos(parseFloat(currentValue));
addToHistory(`cos(${currentValue}) = ${result}`);
break;
case 'tan':
result = Math.tan(parseFloat(currentValue));
addToHistory(`tan(${currentValue}) = ${result}`);
break;
case 'x!':
result = factorial(parseInt(currentValue));
addToHistory(`(${currentValue})! = ${result}`);
break;
case 'π':
result = Math.PI;
addToHistory(`π = ${result}`);
break;
case 'e':
result = Math.E;
addToHistory(`e = ${result}`);
break;
default:
return;
}
currentValue = result.toString();
display.textContent = currentValue;
} catch (error) {
currentValue = 'Error';
display.textContent = currentValue;
}
});
});
function factorial(n) {
if (n < 0) throw new Error('Negative factorial');
if (n === 0 || n === 1) return 1;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
}
// Unit Converter Functions
function initUnitConverter() {
const conversionType = document.getElementById('conversionType');
const fromUnit = document.getElementById('fromUnit');
const toUnit = document.getElementById('toUnit');
const converterInput = document.getElementById('converterInput');
const convertBtn = document.getElementById('convertBtn');
const resultDisplay = document.querySelector('.unit-converter .conversion-result');
const conversionOptions = {
length: ['meter', 'kilometer', 'centimeter', 'millimeter', 'mile', 'yard', 'foot', 'inch'],
weight: ['kilogram', 'gram', 'milligram', 'pound', 'ounce', 'ton'],
temperature: ['celsius', 'fahrenheit', 'kelvin'],
volume: ['liter', 'milliliter', 'gallon', 'quart', 'pint', 'cup', 'fluid-ounce']
};
// Initialize units
updateUnitOptions();
conversionType.addEventListener('change', updateUnitOptions);
convertBtn.addEventListener('click', convertUnits);
function updateUnitOptions() {
const type = conversionType.value;
const units = conversionOptions[type];
// Clear existing options
fromUnit.innerHTML = '';
toUnit.innerHTML = '';
// Add new options
units.forEach(unit => {
const option1 = document.createElement('option');
option1.value = unit;
option1.textContent = unit;
fromUnit.appendChild(option1);
const option2 = document.createElement('option');
option2.value = unit;
option2.textContent = unit;
toUnit.appendChild(option2);
});
// Set default "to" unit to something different
if (units.length > 1) {
toUnit.selectedIndex = 1;
}
}
function convertUnits() {
const type = conversionType.value;
const from = fromUnit.value;
const to = toUnit.value;
const value = parseFloat(converterInput.value);
if (isNaN(value)) {
resultDisplay.textContent = 'Please enter a valid number';
return;
}
try {
let result;
switch (type) {
case 'length':
result = convertLength(value, from, to);
break;
case 'weight':
result = convertWeight(value, from, to);
break;
case 'temperature':
result = convertTemperature(value, from, to);
break;
case 'volume':
result = convertVolume(value, from, to);
break;
default:
result = 'Invalid conversion type';
}
addToHistory(`${value} ${from} = ${result} ${to}`);
resultDisplay.textContent = `${value} ${from} = ${result} ${to}`;
} catch (error) {
resultDisplay.textContent = error.message;
}
}
function convertLength(value, from, to) {
const factors = {
meter: 1,
kilometer: 1000,
centimeter: 0.01,
millimeter: 0.001,
mile: 1609.34,
yard: 0.9144,
foot: 0.3048,
inch: 0.0254
};
return convert(value, from, to, factors);
}
function convertWeight(value, from, to) {
const factors = {
kilogram: 1,
gram: 0.001,
milligram: 0.000001,
pound: 0.453592,
ounce: 0.0283495,
ton: 907.185
};
return convert(value, from, to, factors);
}
function convertVolume(value, from, to) {
const factors = {
liter: 1,
milliliter: 0.001,
gallon: 3.78541,
quart: 0.946353,
pint: 0.473176,
cup: 0.24,
'fluid-ounce': 0.0295735
};
return convert(value, from, to, factors);
}
function convertTemperature(value, from, to) {
let celsius;
// Convert to Celsius first
switch (from) {
case 'celsius':
celsius = value;
break;
case 'fahrenheit':
celsius = (value - 32) * 5/9;
break;
case 'kelvin':
celsius = value - 273.15;
break;
default:
throw new Error('Invalid temperature unit');
}
// Convert from Celsius to target unit
switch (to) {
case 'celsius':
return celsius;
case 'fahrenheit':
return (celsius * 9/5) + 32;
case 'kelvin':
return celsius + 273.15;
default:
throw new Error('Invalid temperature unit');
}
}
function convert(value, from, to, factors) {
if (!factors[from] || !factors[to]) {
throw new Error('Invalid units for conversion');
}
const valueInBase = value * factors[from];
return valueInBase / factors[to];
}
}
// Currency Converter Functions
function initCurrencyConverter() {
const fromCurrency = document.getElementById('fromCurrency');
const toCurrency = document.getElementById('toCurrency');
const currencyAmount = document.getElementById('currencyAmount');
const convertCurrencyBtn = document.getElementById('convertCurrencyBtn');
const exchangeRateDisplay = document.getElementById('exchangeRate');
const currencyResultDisplay = document.getElementById('currencyResult');
// Sample exchange rates (in a real app, you would fetch these from an API)
const exchangeRates = {
USD: { EUR: 0.85, GBP: 0.73, JPY: 110.25, INR: 74.50 },
EUR: { USD: 1.18, GBP: 0.86, JPY: 129.75, INR: 87.60 },
GBP: { USD: 1.37, EUR: 1.16, JPY: 151.25, INR: 102.10 },
JPY: { USD: 0.0091, EUR: 0.0077, GBP: 0.0066, INR: 0.68 },
INR: { USD: 0.013, EUR: 0.011, GBP: 0.0098, JPY: 1.47 }
};
convertCurrencyBtn.addEventListener('click', convertCurrency);
function convertCurrency() {
const amount = parseFloat(currencyAmount.value);
const from = fromCurrency.value;
const to = toCurrency.value;
if (isNaN(amount) || amount <= 0) {
currencyResultDisplay.textContent = 'Please enter a valid amount';
return;
}
if (from === to) {
currencyResultDisplay.textContent = `${amount} ${from} = ${amount} ${to}`;
exchangeRateDisplay.textContent = `1 ${from} = 1 ${to}`;
return;
}
try {
const rate = exchangeRates[from][to];
const result = amount * rate;
exchangeRateDisplay.textContent = `1 ${from} = ${rate.toFixed(4)} ${to}`;
currencyResultDisplay.textContent = `${amount.toFixed(2)} ${from} = ${result.toFixed(2)} ${to}`;
addToHistory(`${amount.toFixed(2)} ${from} → ${result.toFixed(2)} ${to}`);
} catch (error) {
currencyResultDisplay.textContent = 'Error converting currency';
exchangeRateDisplay.textContent = '';
}
}
}
// Age Calculator Functions
function initAgeCalculator() {
const birthDateInput = document.getElementById('birthDate');
const calculateAgeBtn = document.getElementById('calculateAgeBtn');
const ageResultDisplay = document.getElementById('ageResult');
// Set max date to today
birthDateInput.max = new Date().toISOString().split('T')[0];
calculateAgeBtn.addEventListener('click', calculateAge);
function calculateAge() {
const birthDate = new Date(birthDateInput.value);
const today = new Date();
if (isNaN(birthDate.getTime())) {
ageResultDisplay.textContent = 'Please select a valid date';
return;
}
if (birthDate > today) {
ageResultDisplay.textContent = 'Birth date cannot be in the future';
return;
}
let years = today.getFullYear() - birthDate.getFullYear();
let months = today.getMonth() - birthDate.getMonth();
let days = today.getDate() - birthDate.getDate();
if (days < 0) {
months--;
// Get the last day of the previous month
const lastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
days += lastMonth.getDate();
}
if (months < 0) {
years--;
months += 12;
}
let ageString = '';
if (years > 0) ageString += `${years} year${years !== 1 ? 's' : ''}`;
if (months > 0) ageString += `${ageString ? ', ' : ''}${months} month${months !== 1 ? 's' : ''}`;
if (days > 0 || ageString === '') ageString += `${ageString ? ', ' : ''}${days} day${days !== 1 ? 's' : ''}`;
ageResultDisplay.innerHTML = `Age: ${ageString}<br>Born on: ${birthDate.toDateString()}`;
addToHistory(`Age calculation for ${birthDate.toDateString()}: ${ageString}`);
}
}
// Formula Solver Functions
function initFormulaSolver() {
const formulaType = document.getElementById('formulaType');
const formulaDescription = document.getElementById('formulaDescription');
const variablesInput = document.getElementById('variablesInput');
const solveFormulaBtn = document.getElementById('solveFormulaBtn');
const formulaResult = document.getElementById('formulaResult');
const solutionSteps = document.getElementById('solutionSteps');
const formulaOptions = {
quadratic: {
description: 'ax² + bx + c = 0',
variables: ['a', 'b', 'c']
},
pythagorean: {
description: 'a² + b² = c² (leave one blank to solve for)',
variables: ['a', 'b', 'c']
},
area_circle: {
description: 'πr²',
variables: ['radius']
},
volume_sphere: {
description: '(4/3)πr³',
variables: ['radius']
},
simple_interest: {
description: 'I = P × r × t',
variables: ['principal (P)', 'rate (r)', 'time (t)']
},
compound_interest: {
description: 'A = P(1 + r/n)^(nt)',
variables: ['principal (P)', 'rate (r)', 'time (t)', 'compounds per year (n)']
}
};
// Initialize formula inputs
updateFormulaInputs();
formulaType.addEventListener('change', updateFormulaInputs);
solveFormulaBtn.addEventListener('click', solveFormula);
function updateFormulaInputs() {
const type = formulaType.value;
const formula = formulaOptions[type];
formulaDescription.textContent = formula.description;
variablesInput.innerHTML = '';
formula.variables.forEach(varName => {
const div = document.createElement('div');
div.className = 'variable-input';
const label = document.createElement('label');
label.textContent = varName + ':';
label.htmlFor = `var-${varName}`;
const input = document.createElement('input');
input.type = 'number';
input.id = `var-${varName}`;
input.placeholder = `Enter ${varName}`;
input.step = 'any';
div.appendChild(label);
div.appendChild(input);
variablesInput.appendChild(div);
});
}
function solveFormula() {
const type = formulaType.value;
const variables = {};
// Get variable values
formulaOptions[type].variables.forEach(varName => {
const inputId = `var-${varName}`;
const input = document.getElementById(inputId);
variables[varName] = input.value === '' ? undefined : parseFloat(input.value);
});
try {
const { solution, solutionSteps: steps } = solveFormulaType(type, variables);
formulaResult.textContent = solution;
solutionSteps.innerHTML = '';
steps.forEach(step => {
const li = document.createElement('li');
li.textContent = step;
solutionSteps.appendChild(li);
});
addToHistory(`${formulaOptions[type].description}: ${solution}`);
} catch (error) {
formulaResult.textContent = `Error: ${error.message}`;
solutionSteps.innerHTML = '';
}
}
function solveFormulaType(type, variables) {
switch (type) {
case 'quadratic':
return solveQuadratic(variables);
case 'pythagorean':
return solvePythagorean(variables);
case 'area_circle':
return solveAreaCircle(variables);
case 'volume_sphere':
return solveVolumeSphere(variables);
case 'simple_interest':
return solveSimpleInterest(variables);
case 'compound_interest':
return solveCompoundInterest(variables);
default:
throw new Error('Unknown formula type');
}
}
function solveQuadratic({ a, b, c }) {
if (a === undefined || b === undefined || c === undefined) {
throw new Error('All coefficients (a, b, c) must be provided');
}
const discriminant = b * b - 4 * a * c;
const steps = [
`Given equation: ${a}x² + ${b}x + ${c} = 0`,
`Discriminant (D) = b² - 4ac = ${b}² - 4*${a}*${c} = ${discriminant}`
];
if (discriminant < 0) {
const realPart = -b / (2 * a);
const imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
steps.push('Discriminant is negative, complex roots exist');
return {
solution: `x = ${realPart.toFixed(2)} ± ${imaginaryPart.toFixed(2)}i`,
solutionSteps: steps
};
} else if (discriminant === 0) {
const root = -b / (2 * a);
steps.push('Discriminant is zero, one real root exists');
return {
solution: `x = ${root.toFixed(2)} (double root)`,
solutionSteps: steps
};
} else {
const root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
const root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
steps.push('Discriminant is positive, two real roots exist');
return {
solution: `x₁ = ${root1.toFixed(2)}, x₂ = ${root2.toFixed(2)}`,
solutionSteps: steps
};
}
}
function solvePythagorean({ a, b, c }) {
const provided = [a, b, c].filter(val => val !== undefined).length;
if (provided !== 2) {
throw new Error('Exactly two of the three variables (a, b, c) must be provided');
}
const steps = [];
let solution;
if (a === undefined) {
steps.push(`Given: b = ${b}, c = ${c}`);
steps.push(`a = √(c² - b²) = √(${c}² - ${b}²)`);
const aSquared = c * c - b * b;
steps.push(`a² = ${aSquared}`);
if (aSquared < 0) throw new Error('Invalid triangle: c must be greater than b');
a = Math.sqrt(aSquared);
steps.push(`a = √${aSquared} = ${a.toFixed(2)}`);
solution = `a = ${a.toFixed(2)}`;
} else if (b === undefined) {
steps.push(`Given: a = ${a}, c = ${c}`);
steps.push(`b = √(c² - a²) = √(${c}² - ${a}²)`);
const bSquared = c * c - a * a;
steps.push(`b² = ${bSquared}`);
if (bSquared < 0) throw new Error('Invalid triangle: c must be greater than a');
b = Math.sqrt(bSquared);
steps.push(`b = √${bSquared} = ${b.toFixed(2)}`);
solution = `b = ${b.toFixed(2)}`;
} else {
steps.push(`Given: a = ${a}, b = ${b}`);
steps.push(`c = √(a² + b²) = √(${a}² + ${b}²)`);
const cSquared = a * a + b * b;
steps.push(`c² = ${cSquared}`);
c = Math.sqrt(cSquared);
steps.push(`c = √${cSquared} = ${c.toFixed(2)}`);
solution = `c = ${c.toFixed(2)}`;
}
return { solution, solutionSteps: steps };
}
function solveAreaCircle({ radius }) {
if (radius === undefined) {
throw new Error('Radius must be provided');
}
const steps = [
`Given radius (r) = ${radius}`,
`Area = πr² = π * ${radius}²`
];
const area = Math.PI * radius * radius;
steps.push(`Area = ${area.toFixed(2)}`);
return {
solution: `Area = ${area.toFixed(2)}`,
solutionSteps: steps
};
}
function solveVolumeSphere({ radius }) {
if (radius === undefined) {
throw new Error('Radius must be provided');
}
const steps = [
`Given radius (r) = ${radius}`,
`Volume = (4/3)πr³ = (4/3)π * ${radius}³`
];
const volume = (4/3) * Math.PI * Math.pow(radius, 3);
steps.push(`Volume = ${volume.toFixed(2)}`);
return {
solution: `Volume = ${volume.toFixed(2)}`,
solutionSteps: steps
};
}
function solveSimpleInterest({ 'principal (P)': P, 'rate (r)': r, 'time (t)': t }) {
if (P === undefined || r === undefined || t === undefined) {
throw new Error('Principal, rate and time must be provided');
}
const steps = [
`Given: Principal (P) = ${P}, Rate (r) = ${r}, Time (t) = ${t}`,
`Simple Interest Formula: I = P × r × t`
];
const interest = P * (r / 100) * t;
const amount = P + interest;
steps.push(`Interest (I) = ${P} × ${r/100} × ${t} = ${interest.toFixed(2)}`);
steps.push(`Total Amount = Principal + Interest = ${P} + ${interest.toFixed(2)} = ${amount.toFixed(2)}`);
return {
solution: `Interest: ${interest.toFixed(2)}, Total Amount: ${amount.toFixed(2)}`,
solutionSteps: steps
};
}
function solveCompoundInterest({ 'principal (P)': P, 'rate (r)': r, 'time (t)': t, 'compounds per year (n)': n }) {
if (P === undefined || r === undefined || t === undefined || n === undefined) {
throw new Error('All parameters must be provided');
}
const steps = [
`Given: Principal (P) = ${P}, Rate (r) = ${r}%, Time (t) = ${t} years, Compounds per year (n) = ${n}`,
`Compound Interest Formula: A = P(1 + r/n)^(nt)`
];
const ratePerPeriod = r / 100 / n;
const periods = n * t;
const amount = P * Math.pow(1 + ratePerPeriod, periods);
const interest = amount - P;
steps.push(`Rate per period (r/n) = ${r/100} / ${n} = ${ratePerPeriod.toFixed(6)}`);
steps.push(`Total periods (nt) = ${n} × ${t} = ${periods}`);
steps.push(`Amount (A) = ${P} × (1 + ${ratePerPeriod.toFixed(6)})^${periods} = ${amount.toFixed(2)}`);
steps.push(`Interest = Amount - Principal = ${amount.toFixed(2)} - ${P} = ${interest.toFixed(2)}`);
return {
solution: `Amount: ${amount.toFixed(2)}, Interest: ${interest.toFixed(2)}`,
solutionSteps: steps
};
}
}
// Initialize history list
if (historyList.children.length === 0) {
historyList.innerHTML = '<li class="empty-history">No history yet</li>';
}
});