All files / optimization binaryExp.ts

100% Statements 10/10
91.66% Branches 11/12
100% Functions 2/2
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28                96x   96x 45x     51x 51x   96x       47x 45x 45x 45x      
/*
 * @copyright Microsoft Corporation. All rights reserved.
 */
import { BinaryExpression, Node, SyntaxKind, ts } from 'ts-morph';
import { isFalsy, isTruthyConstExpr, tryReplaceParentParentheses } from '../utils';
import { HandlerReturnType } from './optimize';
 
export function handleBinaryExp(exp: BinaryExpression): HandlerReturnType {
  const operator = exp.getOperatorToken().getKind();
  let newWork: HandlerReturnType;
  if (operator === SyntaxKind.AmpersandAmpersandToken) {
    newWork = exp.getFirstChild(isFalsy) // if there's a falsy child
      ? exp.replaceWithText('false')
      : simplify(exp, isTruthyConstExpr);
  } else Eif (operator === SyntaxKind.BarBarToken) {
    newWork = exp.getFirstChild(isTruthyConstExpr) ? exp.replaceWithText('true') : simplify(exp, isFalsy);
  }
  return tryReplaceParentParentheses(newWork);
}
 
function simplify(exp: BinaryExpression, cond: (node: Node<ts.Node>) => boolean): HandlerReturnType {
  if (exp.getFirstChild(cond)) {
    const lhs = exp.getLeft();
    const rhs = exp.getRight();
    return cond(lhs) ? exp.replaceWithText(rhs.getText()) : exp.replaceWithText(lhs.getText());
  }
}