Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Calculator Logic #2

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 41 additions & 3 deletions src/app-components/CalculatorApp.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,49 @@
import { FC, useState } from 'react'

const AVAILABLE_OPERATORS = ['/', '*', '+', '-']

const CalculatorApp: FC<any> = () => {
const [foo, setFoo] = useState('foo')
const [equationArray, setEquationArray] = useState<string[]>([])

const handleButtonClick = (value: string) => {
if (isOperator(value) && (!equationsInArray() || isOperator(lastEnteredEquation()))) return

if (isNumber(value) && equationsInArray() && isNumber(lastEnteredEquation())) {
const newNumber = lastEnteredEquation() + value
const newEquationArr = replaceLastEquation(newNumber)
setEquationArray(newEquationArr)
return
}

setEquationArray([...equationArray, value])
}

const isOperator = (value: string): boolean => AVAILABLE_OPERATORS.includes(value)
const isNumber = (value: string): boolean => !isOperator(value)
const equationsInArray = (): boolean => equationArray.length > 0
const lastEnteredEquation = (): string => equationArray[equationArray.length - 1]

const replaceLastEquation = (replaceValue: string): string[] => {
const eqArr = [...equationArray]
eqArr.splice(equationArray.length -1, 1, replaceValue)
return eqArr
}

console.log(equationArray)

return (
<div>
<p>Calculator App: { foo }</p>
<button onClick={() => setFoo('bar')}>Bar</button>
{
[...Array(10)].map((_, i) => (
<button key={i} onClick={() => handleButtonClick(i.toString())}>{ i }</button>
))
}
{
AVAILABLE_OPERATORS.map(operator => (
<button onClick={() => handleButtonClick(operator)}>{ operator }</button>
))
}
<button>=</button>
</div>
)
}
Expand Down