Hey guys I was wondering if it is possible to make a regex for the calculator input with these conditions, the display starts with a 0
:
- the fist char can be an
+
or-
sign (optional) - if the first input is a
.
it should be appended to the0
- if the first input is a number it should take the place of the
0
- the number can have only one
.
- after a number I can have an operator
+-/*
- the operator
/*
can be followed by an+-
- if the input is an operator and the last char is a operator it should take the place of the last char
I could do that with a mix of regex
and conditionals
but i think it’s not the idea of a clean code:
const displayPattern = /([+-]?)(\d+)(\.?)(\d*)([*/]?)([+-]?)/g;
const isOperator = /[-+*/]/;
const isNumber = /\d/;
const isSign = /[-+]/;
const lastChar = state.slice(-1);
if (value.includes('AC')) {
setState('0');
} else if (state.length === 1) {
if (isNumber.test(value)) {
if (state === '0') {
setState(value);
} else {
setState(preVal => preVal + value);
}
} else if (value === '.') {
setState(preVal => preVal + value);
} else if (isSign.test(value)) {
setState(value);
}
} else {
if (isOperator.test(lastChar) && isOperator.test(value)) {
if (isSign.test(lastChar)) {
setState(prevVal => prevVal.slice(0, -1) + value);
} else {
!isSign.test(value) &&
setState(prevVal => prevVal.slice(0, -1) + value);
}
}
setState(
preVal =>
(preVal + value).match(displayPattern) &&
(preVal + value).match(displayPattern).join('')
);
}