All files / json-crdt-extensions/peritext/slice util.ts

57.57% Statements 19/33
34.78% Branches 8/23
50% Functions 1/2
60% Lines 15/25

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 41 42 43 44 4561x     61x 15182x     14454x   728x 728x 728x 728x 1795x 1795x     1638x   157x 157x         728x             61x                        
import {SliceTypeName} from './constants';
import type {SliceType, SliceTypeStep} from '../slice/types';
 
export const validateType = (type: SliceType) => {
  switch (typeof type) {
    case 'string':
    case 'number':
      return;
    case 'object': {
      Iif (!(type instanceof Array)) throw new Error('INVALID_TYPE');
      Iif (type.length > 32) throw new Error('INVALID_TYPE');
      const length = type.length;
      LOOP: for (let i = 0; i < length; i++) {
        const step = type[i];
        switch (typeof step) {
          case 'string':
          case 'number':
            continue LOOP;
          case 'object':
            Iif (!Array.isArray(step) || step.length !== 2) throw new Error('INVALID_TYPE');
            continue LOOP;
          default:
            throw new Error('INVALID_TYPE');
        }
      }
      return;
    }
    default:
      throw new Error('INVALID_TYPE');
  }
};
 
export const formatType = (step: SliceTypeStep): string => {
  let tag: string | number = '';
  let discriminant: number = -1;
  if (Array.isArray(step)) {
    tag = step[0];
    discriminant = step[1];
  } else {
    tag = step;
  }
  Iif (typeof tag === 'number' && Math.abs(tag) <= 64 && SliceTypeName[tag]) tag = SliceTypeName[tag] ?? tag;
  return '<' + tag + (discriminant >= 0 ? ':' + discriminant : '') + '>';
};