Bit of a bloated question, so I'll lay it out in steps
I have three variables
let operators: = ['+', '−', '*', '/'];
The current user input (lets call it currentUserInput
)
and the newUserInput
(Whatever the user just typed)
I need to:
newUserInput
contains any of the operatorscurrentUserInput
, otherwise, add it to the endcurrentUserInput
, replace it with the new one.Example
If the currentUserInput
is +1234
and the user types /
anywhere in the input field, the new currentUserInput
should be /1234
I have been using if(operators.some(function(v) { return newUserInput.indexOf(v) >= 0; }))
For step 1, which will give me a boolean response, but I need the operator being used as the response.
So the idea is to append to the end of the string unless they have an operator as the new input? And if they have an operator already then replace the current operator otherwise prepend it. Assuming you want to do that try this code:
function processInput(currentInput, newUserInput) {
let operators = ['+', '-', '*', '/'];
if(operators.includes(newUserInput)) {
var containsOperator = operators.some(operator => operator == currentInput[0]);
return newUserInput + (containsOperator ? currentInput.substr(1) : currentInput);
} else {
return currentInput + newUserInput;
}
}
console.log(processInput("-string", "+"));
console.log(processInput("-string", "s"));
console.log(processInput("string", "+"));
console.log(processInput("string", "s"));