Created
December 12, 2018 17:35
-
-
Save NikitaGlukhi/01383bf4acb01c55946a6d72059dc787 to your computer and use it in GitHub Desktop.
Route calculator. Final solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function calculate(str){ | |
let result = ''; | |
let num = ''; | |
let arrayOfElements = []; | |
if(/[^0-9\.\$\+\-\*]/.test(str)) { | |
return '400: Bad request'; | |
} else { | |
for (let i = 0; i < str.length; i++) { | |
if (str[i] === "$") { | |
arrayOfElements.push(num); | |
arrayOfElements.push(str[i]); | |
num = ''; | |
} else if (str[i] === "*") { | |
arrayOfElements.push(num); | |
arrayOfElements.push(str[i]); | |
num = ''; | |
} else if (str[i] === "-") { | |
arrayOfElements.push(num); | |
arrayOfElements.push(str[i]); | |
num = ''; | |
} else if (str[i] === "+") { | |
arrayOfElements.push(num); | |
arrayOfElements.push(str[i]); | |
num = ''; | |
} else if (i === str.length-1) { | |
num = num + str[i]; | |
arrayOfElements.push(num); | |
} else if (+str[i] === 0 || str[i] === ".") { | |
num = num + str[i]; | |
} else if (+str[i] > 0 || str[i] === ".") { | |
num = num + str[i]; | |
} | |
} | |
} | |
function operations(array) { | |
array.forEach((element, index) => { | |
if (array[index] === "$") { | |
result = result + (+array[index - 1] / +array[index + 1]); | |
arrayOfElements.splice(index - 1, 3, result); | |
result = ''; | |
operations(array); | |
} | |
}); | |
array.forEach((element, index) => { | |
if (array[index] === "*") { | |
result = result + (+array[index - 1] * +array[index + 1]); | |
arrayOfElements.splice(index - 1, 3, result); | |
result = ''; | |
operations(array); | |
} | |
}); | |
array.forEach((element, index) => { | |
if (array[index] === "-") { | |
result = result + (+array[index - 1] - +array[index + 1]); | |
arrayOfElements.splice(index - 1, 3, result); | |
result = ''; | |
operations(array); | |
} | |
}); | |
array.forEach((element, index) => { | |
if (array[index] === "+") { | |
result = result + (+array[index - 1] + +array[index + 1]); | |
arrayOfElements.splice(index - 1, 3, result); | |
result = ''; | |
operations(array); | |
} | |
}) | |
} | |
operations(arrayOfElements); | |
return +arrayOfElements[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment