export const answer = (question) => {
const match = question.match(/^What is (.*)\?$/);
if (!match) throw new Error('Unknown operation');
const tokens = match[1]
.replace(/plus/g, '+')
.replace(/minus/g, '-')
.replace(/multiplied by/g, '*')
.replace(/divided by/g, '/')
.split(' ');
if (tokens.length === 0 || tokens[0] === '') throw new Error('Unknown operation');
let res = parseInt(tokens[0]);
if (isNaN(res)) throw new Error('Unknown operation');
for (let i = 1; i < tokens.length; i += 2) {
const op = tokens[i];
const val = parseInt(tokens[i + 1]);
if (isNaN(val)) {
if (tokens[i] && !['+', '-', '*', '/'].includes(tokens[i])) {
throw new Error('Unknown operation');
}
throw new Error('Syntax error');
}
switch (op) {
case '+': res += val; break;
case '-': res -= val; break;
case '*': res *= val; break;
case '/': res /= val; break;
default: throw new Error('Unknown operation');
}
}
return res;
};