All files / src/shared/lib/helpers symbols.ts

81.25% Statements 26/32
100% Branches 3/3
25% Functions 2/8
100% Lines 18/18

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          41x 76x               76x   1x   75x                   41x       13x 13x 13x 13x 7x   13x     41x 41x 41x 41x 41x 41x  
/**
 * Converts a string into a valid C symbol
 * @param inputSymbol Preferred name for symbol
 * @returns valid C symbol
 */
export const toValidSymbol = (inputSymbol: string) => {
  const symbol = String(inputSymbol || "symbol")
    .toLowerCase()
    // Strip anything but alphanumeric
    .replace(/[^a-z0-9_]/g, "_")
    // Squash repeating underscores
    .replace(/[_]+/g, "_")
    // Limit to 27 chars to leave room for _NNN postfix while keeping within C's 31 unique char limit
    .substring(0, 27);
  if (symbol.match(/^\d/)) {
    // Starts with a number
    return `_${symbol}`;
  }
  return symbol;
};
 
/**
 * Generates the next unique symbol given a preferred name and an array of existing symbols.
 * When symbol already exists will append an incrementing numeric value
 * @param inputSymbol Preferred name for symbol
 * @param existingSymbols Array of existing symbols
 * @returns unique C symbol
 */
export const genSymbol = (
  inputSymbol: string,
  existingSymbols: Set<string>
) => {
  const initialSymbol = toValidSymbol(inputSymbol);
  let symbol = initialSymbol;
  let count = 0;
  while (existingSymbols.has(symbol)) {
    symbol = `${initialSymbol.replace(/_[0-9]+/, "")}_${count++}`;
  }
  return symbol;
};
 
export const tilesetSymbol = (symbol: string) => `${symbol}_tileset`;
export const tilemapSymbol = (symbol: string) => `${symbol}_tilemap`;
export const tilemapAttrSymbol = (symbol: string) => `${symbol}_tilemap_attr`;
export const initScriptSymbol = (symbol: string) => `${symbol}_init`;
export const interactScriptSymbol = (symbol: string) => `${symbol}_interact`;
export const updateScriptSymbol = (symbol: string) => `${symbol}_update`;