blade-sensei / learning

Roadmap for software engineer, sandbox, algorithms training, it also contains my daily task dashboard
9 stars 2 forks source link

algo: get number left and side in calcul expression STRING (operators) #58

Closed blade-sensei closed 4 years ago

blade-sensei commented 4 years ago

Setps

First need to get the operator prioprity like * or / To execute first then search for the left and right side operands

left right side

etRightOperand(expression, index) {
    let rightLimit = expression.length;
    let leftLimit = index + 1;
    for (let endIndex = leftLimit; endIndex < expression.length; endIndex++) {
      const term = expression[endIndex];
      if (this.isOperator(term)) {
        rightLimit  = endIndex;
        break;
      }
    }
    let number = expression.slice(leftLimit, rightLimit);
    number = number.join('');
    number = Number(number);
    return [number, rightLimit - 1]
  }

  getLeftOperand(expression, index) {
    let leftLimit = 0;
    for (let endIndex = index - 1; endIndex >= 0; endIndex--) {
      const term = expression[endIndex];
      if (this.isOperator(term)) {
        leftLimit  = endIndex + 1;
        break;
      }
    }
    let number = expression.slice(leftLimit, index);
    number = number.join('');
    number = Number(number);
    return [number, leftLimit]
  }

priority sign index


 let firstOperatorFound = false;
    let indexPriorityOperator;
    let operands = [];

    for (let [index, term] of expression.entries()) {
      if (this.isOperator(term)) {
        if (this.isPriorityOperator(term)) {
          indexPriorityOperator = index;
          break;
        } if (!firstOperatorFound) {
          indexPriorityOperator = index;
          firstOperatorFound = true;
        }
      }
    }