Assert Function

The assert function validates conditions and throws errors when assertions fail. It’s used for runtime validation and error handling.

Signature

util.assert(expected: boolean, errorMessage: string): void

Parameters

  • expected: Boolean condition to evaluate
  • errorMessage: Error message to display if assertion fails

Return Value

  • Returns: void
  • Throws: Error with provided message if assertion fails

Usage Examples

CODE_STEP
// Basic assertion
util.assert(typeof input.value === 'string', 'Input value must be a string');

// Complex condition
util.assert(
  Array.isArray(input.items) && input.items.length > 0,
  'Items array must not be empty'
);

// Validation chain
util.assert(input.amount > 0, 'Amount must be positive');
util.assert(input.amount <= 1000, 'Amount cannot exceed 1000');

Best Practices

  1. Use descriptive error messages
  2. Check critical conditions early
  3. Chain multiple assertions for complex validation

Common Patterns

CODE_STEP
// Input validation
util.assert(input.document, 'Document is required');
util.assert(
  typeof input.document.file_id === 'string',
  'Invalid document file_id'
);

// Array validation
util.assert(Array.isArray(input.categories), 'Categories must be an array');

// Numeric range validation
util.assert(
  input.score >= 0 && input.score <= 100,
  'Score must be between 0 and 100'
);

Parse Function

Parses text that may contain JSON into JavaScript objects. Extracts and parses JSON-like content from text, returning the original input if parsing fails.

Signature

util.parse(text: unknown): any

Parameters

  • text: Text to parse (can be any type)
  • If text is not a string, returns the original input unchanged
  • If text is a string, attempts to extract JSON-like content (objects/arrays) before parsing

Return Value

  • Returns: Parsed JavaScript object if valid JSON is found and parsed successfully
  • Returns: Original input if input is not a string
  • Returns: Original input if no valid JSON content is found
  • Throws: JSON.parse errors if invalid JSON syntax is encountered

Usage Examples

CODE_STEP
// Parse complete JSON string
const data = util.parse('{"key": "value"}');
// Result: { key: "value" }

// Parse JSON embedded in text
const embedded = util.parse('Some text {"key": "value"} more text');
// Result: { key: "value" }

// Parse array in text
const array = util.parse('prefix [1,2,3] suffix');
// Result: [1,2,3]

// Non-string input returns unchanged
const nullValue = util.parse(null);
// Result: null

// No JSON content returns original
const plainText = util.parse('just plain text');
// Result: "just plain text"

Best Practices

  1. Always validate the parsed result matches expected type/structure
  2. Handle parsing errors with try/catch if needed
  3. Be aware that embedded JSON will be extracted and parsed

Common Patterns

CODE_STEP
// Safe parsing with validation
const parseConfig = (input) => {
  const config = util.parse(input.config);
  util.assert(
    typeof config === 'object' && config !== null,
    'Invalid config format'
  );
  return config;
};

// Parse with default values
const parseOptions = (input) => {
  const options = util.parse(input.options) || {};
  return {
    timeout: options.timeout || 5000,
    retries: options.retries || 3,
  };
};

File Operations

For information about file operations, see the Accessing File Contents and Images documentation.

Number Formatting

Formats numbers using locale-specific formatting rules. Supports various number formats and styles.

formatNumber

Signature

util.formatNumber(
  number: number,
  options?: Intl.NumberFormatOptions
): string

Parameters

  • number: Number to format
  • options: Optional Intl.NumberFormatOptions object

Return Value

  • Returns: Formatted number string

Usage Examples

CODE_STEP
// Basic formatting
util.formatNumber(1234.567);
// Result: "1,234.567"

// Custom precision
util.formatNumber(1234.567, { maximumFractionDigits: 2 });
// Result: "1,234.57"

// Percentage
util.formatNumber(0.1234, { style: 'percent' });
// Result: "12.34%"

// Custom grouping
util.formatNumber(1234567, {
  useGrouping: true,
  minimumFractionDigits: 0,
});
// Result: "1,234,567"

Best Practices

  1. Specify precision requirements
  2. Consider locale implications
  3. Handle negative numbers appropriately
  4. Use consistent formatting options

formatCurrency

Signature

util.formatCurrency(
  number: number,
  options?: Intl.NumberFormatOptions
): string

Description

Formats numbers as currency values. Defaults to USD if no currency specified.

Parameters

  • number: Number to format as currency
  • options: Optional Intl.NumberFormatOptions object

Return Value

  • Returns: Formatted currency string

Usage Examples

CODE_STEP
// Basic USD formatting
util.formatCurrency(1234.567);
// Result: "$1,234.57"

// Custom currency
util.formatCurrency(1234.567, { currency: 'EUR' });
// Result: "€1,234.57"

// Custom precision
util.formatCurrency(1234.567, {
  currency: 'JPY',
  maximumFractionDigits: 0,
});
// Result: "¥1,235"

// Negative values
util.formatCurrency(-1234.567);
// Result: "-$1,234.57"

Best Practices

  1. Specify currency code when not USD
  2. Consider currency-specific conventions
  3. Handle zero and negative amounts properly
  4. Use consistent currency formatting