Skip to content

Instantly share code, notes, and snippets.

@manduks
Created August 8, 2023 20:37
Show Gist options
  • Save manduks/be18f3b3eb01089b510ad03ae3a966b6 to your computer and use it in GitHub Desktop.
Save manduks/be18f3b3eb01089b510ad03ae3a966b6 to your computer and use it in GitHub Desktop.
'use client';
import { useRef, useState } from 'react';
// create a function that takes an operator and two numbers and returns the result
const calculate = (op: string, a: number, b: number): number => {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '/':
return a / b;
case '*':
return a * b;
case '=':
return b;
default:
return b;
}
};
const operators = ['+', '-', '/', '*', '=', 'clear'];
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
export default function Home() {
const [currentNumber, setCurrentNumber] = useState('');
const [result, setResult] = useState<number | null>(null);
const [input, setInput] = useState('');
const prevOp = useRef('');
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div className="flex flex-col items-center justify-center space-y-4">
<div className="w-[200px] h-12 border border-gray-500 flex justify-end items-center p-2">
{input}
</div>
<div className="w-[300px] flex space-x-2">
{numbers.map((i) => (
<button
key={i}
className="border border-gray-500 w-24"
onClick={() => {
const newNumber = currentNumber.toString() + i;
setCurrentNumber(newNumber);
setInput(newNumber);
}}
>
{i}
</button>
))}
</div>
<div className="w-[200px] flex space-x-2">
{operators.map((op) => (
<button
key={op}
className="border border-gray-500 p-2"
onClick={() => {
if (op === 'clear') {
setCurrentNumber('');
setInput('');
setResult(null);
prevOp.current = '';
return;
}
if (!currentNumber) return;
let calculation;
if (result === null) {
calculation = Number(currentNumber);
setResult(calculation);
}
if (prevOp.current) {
calculation = calculate(
prevOp.current,
result!,
Number(currentNumber)
);
setResult(calculation);
}
prevOp.current = op;
setCurrentNumber('');
setInput(calculation?.toString() || '');
}}
>
{op}
</button>
))}
</div>
</div>
</main>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment