Skip to content

Instantly share code, notes, and snippets.

@davichoso
Created March 17, 2022 20:42
Show Gist options
  • Save davichoso/a94c071c528ff5a6ac1bf655cdffe3d1 to your computer and use it in GitHub Desktop.
Save davichoso/a94c071c528ff5a6ac1bf655cdffe3d1 to your computer and use it in GitHub Desktop.
test
function getNumberToLeftSide(numberToLeft) {
let numbr = ''
let i = 1;
while (!isNaN(numberToLeft[numberToLeft.length - i])) {
numbr = numberToLeft[numberToLeft.length - i] + numbr
i++;
}
return numbr
}
function getNumberToRightSide(numberToRight) {
let numbr = ''
let i = 0
while (!isNaN(numberToRight[i])) {
numbr = numbr + numberToRight[i]
i++
}
return numbr
}
function evalOperator(stringToEval, operator) {
return stringToEval.split(operator).reduce((prev, current) => {
const numberToLeft = getNumberToLeftSide(prev)
const numberToRight = getNumberToRightSide(current)
if (numberToLeft.length > 0 && numberToRight.length > 0) {
let result;
if (operator == '/')
result = numberToLeft / numberToRight
if (operator == '*')
result = numberToLeft * numberToRight
if (operator == '+')
result = (numberToLeft * 1) + (numberToRight * 1)
if (operator == '-')
result = (numberToLeft * 1) - (numberToRight * 1)
return prev.slice(0, -numberToLeft.length) + result + current.slice(numberToRight.length)
}
return prev + operator + current
})
}
function eliminateParenthesis(str) // here we try to find last open (
{
let lastIndex = str.length
while (str.lastIndexOf('(', lastIndex) >0 ) {
const openIndex = str.lastIndexOf('(') // here we find the last open (
const closeIndex = str.indexOf(')', openIndex)
let stringBetween = str.slice(openIndex + 1, closeIndex)
if (!isNaN(stringBetween)) { //just numbers
//here we try to eliminate the parenthesis
//console.log(str[openIndex - 1])
if (openIndex > 0) {
const charBeforeParenthesis = str[openIndex - 1]
if (!isNaN(charBeforeParenthesis) || charBeforeParenthesis == ')') // if is a number or a parenthesis ad * operator
{
stringBetween = '*' + stringBetween
}
}
str = str.slice(0, openIndex) + stringBetween + str.slice(closeIndex + 1)
// if there is a parenthesis
} else {
lastIndex = str.lastIndexOf('(')*1 -1
}
// else the parenthesis still contains operators, do nothing
}
return str
}
function Calculator(str) {
// first we should evaluate posible operations
//while (isNaN(str)) {
str = evalOperator(str, '/');
str = evalOperator(str, '*');
str = evalOperator(str, '+');
str = evalOperator(str, '-');
//after we should try to eliminate parenthesis symbols
str = eliminateParenthesis(str);
//console.log(str)
// }
// code goes here
console.log('------------')
return str;
}
// keep this function call here
console.log(Calculator("2(6)(4/2)+(22*2)(2)"));
console.log(Calculator("2(6)(4/2)+(22*2)(2)"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment