Skip to content

Instantly share code, notes, and snippets.

@NikitaGlukhi
Created December 12, 2018 17:35
Show Gist options
  • Save NikitaGlukhi/01383bf4acb01c55946a6d72059dc787 to your computer and use it in GitHub Desktop.
Save NikitaGlukhi/01383bf4acb01c55946a6d72059dc787 to your computer and use it in GitHub Desktop.
Route calculator. Final solution
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