All files / src/shared/lib/text textCodes.ts

74.29% Statements 26/35
81.25% Branches 13/16
60% Functions 3/5
70% Lines 21/30

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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 748x 8x                       8x                 8x             8x 30x         59x 20x     10x         10x 41x 12x 12x                 29x 5x     29x 2x   29x       10x     8x 23x    
import { ensureNumber } from "shared/types";
import { lexText, Token } from "shared/lib/compiler/lexText";
 
type TextAction = {
  type: "wait";
  frames: number;
};
 
type TokenChunk = {
  tokens: Token[];
  action?: TextAction;
};
 
export const parseWaitCodeValue = (input: string): number | undefined => {
  const waitCode = input.match(/!W:([0-9.]+)([fs])!/);
  Iif (!waitCode) {
    return undefined;
  }
  const time = ensureNumber(parseFloat(waitCode[1]), 30);
  return time;
};
 
export const parseWaitCodeUnits = (input: string): "frames" | "time" => {
  Iif (input[input.length - 2] === "s") {
    return "time";
  }
  return "frames";
};
 
export const chunkTokensOnWaitCodes = (tokens: Token[]): TokenChunk[] => {
  Iif (tokens.length === 0) {
    return [];
  }
 
  // No wait tokens found so just return parsed tokens wrapped in array
  if (!tokens.some((token) => token.type === "wait")) {
    return [{ tokens }];
  }
 
  const output: TokenChunk[] = [{ tokens: [] }];
 
  let lastSpeedToken: (Token & { type: "speed" | "speedVariable" }) | undefined;
  let lastFontToken: (Token & { type: "font" | "fontVariable" }) | undefined;
 
  for (const token of tokens) {
    if (token.type === "wait") {
      output[output.length - 1].action = token;
      output.push({
        tokens: [
          // Apply any speed / font changes from before split
          ...(lastSpeedToken ? [lastSpeedToken] : []),
          ...(lastFontToken ? [lastFontToken] : []),
        ],
      });
    } else {
      // Track speed changes
      if (token.type === "speed" || token.type === "speedVariable") {
        lastSpeedToken = token;
      }
      // Track font changes
      if (token.type === "font" || token.type === "fontVariable") {
        lastFontToken = token;
      }
      output[output.length - 1].tokens.push(token);
    }
  }
 
  return output;
};
 
export const chunkTextOnWaitCodes = (input: string): TokenChunk[] => {
  return chunkTokensOnWaitCodes(lexText(input));
};