Search code examples
javascriptstringlodash

Add / Replace operator to beginning of string with conditionals


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:

  1. See if newUserInput contains any of the operators
  2. If it does, add it to the beginning of currentUserInput, otherwise, add it to the end
  3. If there is already an operator at the beginning of currentUserInput, 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.


Solution

  • 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"));