All files / src/shared/lib/variables variablesInText.ts

100% Statements 15/15
100% Branches 2/2
100% Functions 4/4
100% Lines 12/12

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 441x 1x 1x                   1x 18x               1x       5x 5x 14x 5x                 1x       7x    
import { lexText, Token as TextToken } from "shared/lib/compiler/lexText";
import { normalizeVariableId } from "shared/lib/variables/variableIds";
import {
  expressionToScriptValue,
  variableInScriptValue,
} from "shared/lib/scriptValue/helpers";
 
/**
 * Extracts a variable ID from a dialogue token by removing any leading zeros.
 * @param {TextToken} token - The token to process, expected to be of type 'variable'.
 * @returns {string | undefined} - The variable ID without leading zeros, or undefined if the token is not of type 'variable'.
 */
export const dialogueTokenToVariableId = (token: TextToken) =>
  token.type === "variable" ? normalizeVariableId(token.variableId) : undefined;
 
/**
 * Checks if a given variable ID exists in a dialogue text input.
 * @param {string} variableId - The ID of the variable to search for in the text (without leading zeros).
 * @param {string} input - The dialogue text input to search within.
 * @returns {boolean} - True if the variable ID is found in the text, false otherwise.
 */
export const variableInDialogueText = (
  variableId: string,
  input: string,
): boolean => {
  const textTokens = lexText(input);
  const isMatch = (token: TextToken) =>
    dialogueTokenToVariableId(token) === variableId;
  return textTokens.some(isMatch);
};
 
/**
 * Checks if a given variable ID exists in an expression text input.
 * @param {string} variableId - The ID of the variable to search for in the expression (without leading zeros).
 * @param {string} input - The expression text input to search within.
 * @returns {boolean} - True if the variable ID is found in the expression, false otherwise.
 */
export const variableInExpressionText = (
  variableId: string,
  input: string,
): boolean => {
  return variableInScriptValue(variableId, expressionToScriptValue(input));
};