All files / json-ot/types/ot-binary-irreversible validate.ts

87.17% Statements 34/39
73.91% Branches 17/23
100% Functions 2/2
96.42% Lines 27/28

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 29 30 31 32 33 34 35 36 37 38 39 40    3x 3x 3x 3x 3x 3x     3x 13x 13x   13x 26x 26x 15x 14x 13x 10x 10x   3x 3x   11x 11x 7x 7x       19x   6x 6x 3x    
import type {BinaryOp, BinaryOpComponent} from './types';
 
export enum VALIDATE_RESULT {
  SUCCESS = 0,
  INVALID_OP = 1,
  INVALID_COMPONENT = 2,
  ADJACENT_SAME_TYPE = 3,
  NO_TRAILING_RETAIN = 4,
}
 
export const validate = (op: BinaryOp): VALIDATE_RESULT => {
  Iif (!(op instanceof Array)) return VALIDATE_RESULT.INVALID_OP;
  Iif (op.length === 0) return VALIDATE_RESULT.INVALID_OP;
  let last: BinaryOpComponent | undefined;
  for (let i = 0; i < op.length; i++) {
    const component = op[i];
    if (typeof component === 'number') {
      if (!component) return VALIDATE_RESULT.INVALID_COMPONENT;
      if (component !== Math.round(component)) return VALIDATE_RESULT.INVALID_COMPONENT;
      if (component > 0) {
        const lastComponentIsRetain = typeof last === 'number' && last > 0;
        Iif (lastComponentIsRetain) return VALIDATE_RESULT.ADJACENT_SAME_TYPE;
      } else {
        const lastComponentIsDelete = typeof last === 'number' && last < 0;
        Iif (lastComponentIsDelete) return VALIDATE_RESULT.ADJACENT_SAME_TYPE;
      }
    } else if (component instanceof Uint8Array) {
      if (!component.length) return VALIDATE_RESULT.INVALID_COMPONENT;
      const lastComponentIsInsert = last instanceof Uint8Array;
      if (lastComponentIsInsert) return VALIDATE_RESULT.ADJACENT_SAME_TYPE;
    } else E{
      return VALIDATE_RESULT.INVALID_COMPONENT;
    }
    last = component;
  }
  const isLastRetain = typeof last === 'number' && last > 0;
  if (isLastRetain) return VALIDATE_RESULT.NO_TRAILING_RETAIN;
  return VALIDATE_RESULT.SUCCESS;
};