Tell us what’s happening:
I’ve finished the calculator project but the 8th test n on aren’t passing even the app working fine. this id the link for the app to check how it works: https://redapy.github.io/calculator/
This is my code on gitHub for more information :
https://github.com/redapy/calculator
PS: I haven’t add any styles yet because I’m using Styled components but its not working when I add rules inside it. However, I’ll try to solve this problem later but if there is any thought it will be great !!
Your code so far
I have 3 components:
a Wrapper where I put all the states and logic:
const Calculator = () => {
const [display, setDisplay] = useState('0');
const [formula, setFormula] = useState('');
const lastPressed = useRef('')
const handleInput = (value, type) => {
//Clear and Initita the states
if (type === 'clear') {
setDisplay('0');
setFormula('');
}
//to prevent multipule zeros at the starts
else if (formula === "0") {
if (value==="0"){ return;}
else {
setFormula(value)
}
}
//in case, 2 or more operators are entered consecutively
else if (type === 'opertor' && lastPressed.current==='opertor') {
//exclude the minus from the rule
if (value === "-") {
console.log(-1)
setDisplay(value);
setFormula(formula+value);
//for the other opertors
} else {
setDisplay(value);
setFormula(formula.replace(/[-+*\/]$/, value))
}
}
//prevent more than one decimal point
else if (type === 'decimal' && lastPressed.current === 'decimal') {
return;
}
//evalute the result
else if (type === "equal") {
let result = eval(formula).toString();
setDisplay(result);
setFormula(result);
lastPressed.current = type
}
//start a new calculation that operates on the result of the previous evaluation
else if (lastPressed.current ==="equal" && type === "opertor") {
setDisplay(display);
setFormula(display+value)
}
//display values and the formula
else {
setDisplay(value);
setFormula(formula+value);
lastPressed.current = type
}
};
return (
<Warapper className="warapper">
<Display display={display} formula={formula} />
<ButtonsList buttons={buttons} handleInput={handleInput}/>
</Warapper>
);
}
a display component:
const Display = ({display, formula}) => {
return (
<Container id="display">
<Result>{formula}</Result>
<Value>{display}</Value>
</Container>
);
}
and the list of buttons:
const ButtonsList = ({buttons, handleInput}) => {
return (
<Grid>
{buttons.map(button => (
<Button
key={button.id}
id={button.id}
onClick = {() => handleInput(button.value, button.type)}
>{button.value}</Button>
))}
</Grid>
);
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36
Challenge: Build a JavaScript Calculator
Link to the challenge: