or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdlocale-options.mdmathematical.mdnumber-formatting.mdutilities.mdvalidation.md
tile.json

utilities.mddocs/

Utility Functions

Internal utilities for slot management, memoization, property operations, and other helper functions used throughout the FormatJS ecosystem. These functions provide essential infrastructure for internationalization operations.

Capabilities

Internal Slot Management

Functions for managing internal slots in internationalization objects using WeakMaps.

/**
 * Sets a single internal slot value for an instance
 * @param map - WeakMap storing internal slots
 * @param pl - Instance to set slot for
 * @param field - Field name to set
 * @param value - Value to set for the field
 */
function setInternalSlot<
  Instance extends object,
  Internal extends object,
  Field extends keyof Internal
>(
  map: WeakMap<Instance, Internal>,
  pl: Instance,
  field: Field,
  value: NonNullable<Internal>[Field]
): void;

/**
 * Sets multiple internal slot values for an instance
 * @param map - WeakMap storing internal slots
 * @param pl - Instance to set slots for
 * @param props - Object containing field-value pairs to set
 */
function setMultiInternalSlots<
  Instance extends object,
  Internal extends object,
  K extends keyof Internal
>(
  map: WeakMap<Instance, Internal>,
  pl: Instance,
  props: Pick<NonNullable<Internal>, K>
): void;

/**
 * Gets a single internal slot value for an instance
 * @param map - WeakMap storing internal slots
 * @param pl - Instance to get slot from
 * @param field - Field name to get
 * @returns Value of the specified field
 * @throws TypeError if instance has no internal slots
 */
function getInternalSlot<
  Instance extends object,
  Internal extends object,
  Field extends keyof Internal
>(
  map: WeakMap<Instance, Internal>,
  pl: Instance,
  field: Field
): Internal[Field];

/**
 * Gets multiple internal slot values for an instance
 * @param map - WeakMap storing internal slots
 * @param pl - Instance to get slots from
 * @param fields - Field names to get
 * @returns Object containing requested field-value pairs
 * @throws TypeError if instance has no internal slots
 */
function getMultiInternalSlots<
  Instance extends object,
  Internal extends object,
  Field extends keyof Internal
>(
  map: WeakMap<Instance, Internal>,
  pl: Instance,
  ...fields: Field[]
): Pick<Internal, Field>;

Usage Examples:

import { 
  setInternalSlot,
  setMultiInternalSlots,
  getInternalSlot,
  getMultiInternalSlots
} from "@formatjs/ecma402-abstract";

// Create a WeakMap for internal slots
const internalSlots = new WeakMap<Intl.NumberFormat, NumberFormatInternal>();
const nf = new Intl.NumberFormat();

// Set single slot
setInternalSlot(internalSlots, nf, 'locale', 'en-US');

// Set multiple slots
setMultiInternalSlots(internalSlots, nf, {
  style: 'decimal',
  notation: 'standard',
  useGrouping: true
});

// Get single slot
const locale = getInternalSlot(internalSlots, nf, 'locale');
console.log(locale); // 'en-US'

// Get multiple slots
const options = getMultiInternalSlots(internalSlots, nf, 'style', 'notation');
console.log(options); // { style: 'decimal', notation: 'standard' }

Property Operations

Functions for defining and creating properties on objects following ECMAScript specifications.

/**
 * Defines a property on target object with specific attributes
 * @param target - Object to define property on
 * @param name - Property name or symbol
 * @param descriptor - Property descriptor with value
 */
function defineProperty<T extends object>(
  target: T,
  name: string | symbol,
  { value }: { value: any } & ThisType<any>
): void;

/**
 * Creates a data property on target object (enumerable, writable, configurable)
 * @param target - Object to create property on
 * @param name - Property name or symbol
 * @param value - Property value
 */
function createDataProperty<T extends object>(
  target: T,
  name: string | symbol,
  value: any
): void;

Usage Examples:

import { defineProperty, createDataProperty } from "@formatjs/ecma402-abstract";

const obj = {};

// Define property (non-enumerable by default)
defineProperty(obj, 'hiddenProp', { value: 'secret' });
console.log(Object.keys(obj)); // [] (not enumerable)
console.log(obj.hiddenProp); // 'secret'

// Create data property (enumerable)
createDataProperty(obj, 'visibleProp', 'visible');
console.log(Object.keys(obj)); // ['visibleProp']
console.log(obj.visibleProp); // 'visible'

String Utilities

String manipulation and processing utilities.

/**
 * Repeats a string a specified number of times
 * @param s - String to repeat
 * @param times - Number of times to repeat
 * @returns Repeated string
 */
function repeat(s: string, times: number): string;

/**
 * Regular expression for Unicode extension sequences
 */
const UNICODE_EXTENSION_SEQUENCE_REGEX: RegExp;

/**
 * Regular expression for Unicode symbol characters
 */
const S_UNICODE_REGEX: RegExp;

Usage Examples:

import { repeat, UNICODE_EXTENSION_SEQUENCE_REGEX, S_UNICODE_REGEX } from "@formatjs/ecma402-abstract";

// Repeat string
console.log(repeat('abc', 3)); // 'abcabcabc'
console.log(repeat('x', 0)); // ''
console.log(repeat('hello', 2)); // 'hellohello'

// Unicode extension regex
const locale = 'en-US-u-ca-buddhist-nu-thai';
const extensions = locale.match(UNICODE_EXTENSION_SEQUENCE_REGEX);
console.log(extensions); // ['-u-ca-buddhist-nu-thai']

// Unicode symbol regex
const text = 'Hello $ World';
const symbols = text.match(S_UNICODE_REGEX);
console.log(symbols); // ['$']

Type Guards and Validation

Functions for type checking and validation.

/**
 * Type guard for literal pattern parts
 * @param patternPart - Pattern part to check
 * @returns true if pattern part is a literal part
 */
function isLiteralPart(
  patternPart: LiteralPart | { type: string; value?: string }
): patternPart is LiteralPart;

/**
 * Assertion function for invariant conditions
 * @param condition - Condition to assert
 * @param message - Error message if condition fails
 * @param Err - Error constructor to use (defaults to Error)
 * @throws Error if condition is false
 */
function invariant(
  condition: boolean,
  message: string,
  Err?: any
): asserts condition;

Usage Examples:

import { isLiteralPart, invariant, LiteralPart } from "@formatjs/ecma402-abstract";

// Type guard usage
const part: LiteralPart | { type: 'element'; value: string } = {
  type: 'literal',
  value: 'Hello'
};

if (isLiteralPart(part)) {
  console.log(part.value); // TypeScript knows this is LiteralPart
}

// Invariant assertion
function divide(a: number, b: number): number {
  invariant(b !== 0, 'Division by zero is not allowed');
  return a / b;
}

console.log(divide(10, 2)); // 5
// divide(10, 0); // Throws Error: Division by zero is not allowed

Memoization Functions

Memoized factory functions for creating Intl objects with performance optimization.

/**
 * Creates memoized NumberFormat instances
 * @param args - Arguments for Intl.NumberFormat constructor
 * @returns Memoized NumberFormat instance
 */
const createMemoizedNumberFormat: (
  ...args: ConstructorParameters<typeof Intl.NumberFormat>
) => Intl.NumberFormat;

/**
 * Creates memoized DateTimeFormat instances
 * @param args - Arguments for Intl.DateTimeFormat constructor
 * @returns Memoized DateTimeFormat instance
 */
const createMemoizedDateTimeFormat: (
  ...args: ConstructorParameters<typeof Intl.DateTimeFormat>
) => Intl.DateTimeFormat;

/**
 * Creates memoized PluralRules instances
 * @param args - Arguments for Intl.PluralRules constructor
 * @returns Memoized PluralRules instance
 */
const createMemoizedPluralRules: (
  ...args: ConstructorParameters<typeof Intl.PluralRules>
) => Intl.PluralRules;

/**
 * Creates memoized Locale instances
 * @param args - Arguments for Intl.Locale constructor
 * @returns Memoized Locale instance
 */
const createMemoizedLocale: (
  ...args: ConstructorParameters<typeof Intl.Locale>
) => Intl.Locale;

/**
 * Creates memoized ListFormat instances
 * @param args - Arguments for Intl.ListFormat constructor
 * @returns Memoized ListFormat instance
 */
const createMemoizedListFormat: (
  ...args: ConstructorParameters<typeof Intl.ListFormat>
) => Intl.ListFormat;

Usage Examples:

import { 
  createMemoizedNumberFormat,
  createMemoizedDateTimeFormat,
  createMemoizedLocale
} from "@formatjs/ecma402-abstract";

// Create memoized formatters (subsequent calls with same args return cached instances)
const nf1 = createMemoizedNumberFormat('en-US', { style: 'currency', currency: 'USD' });
const nf2 = createMemoizedNumberFormat('en-US', { style: 'currency', currency: 'USD' });
console.log(nf1 === nf2); // true (same instance from cache)

const dtf1 = createMemoizedDateTimeFormat('en-US', { year: 'numeric', month: 'long' });
const dtf2 = createMemoizedDateTimeFormat('en-US', { year: 'numeric', month: 'long' });
console.log(dtf1 === dtf2); // true (same instance from cache)

const locale1 = createMemoizedLocale('en-US');
const locale2 = createMemoizedLocale('en-US');
console.log(locale1 === locale2); // true (same instance from cache)

Error Handling

Functions for checking and handling locale data errors.

/**
 * Checks if an error is a missing locale data error
 * @param e - Error to check
 * @returns true if error indicates missing locale data
 */
function isMissingLocaleDataError(e: Error): boolean;

Usage Examples:

import { isMissingLocaleDataError } from "@formatjs/ecma402-abstract";

try {
  // Some operation that might fail due to missing locale data
  someLocaleOperation();
} catch (error) {
  if (isMissingLocaleDataError(error)) {
    console.log('Missing locale data, using fallback');
    // Handle missing locale data scenario
  } else {
    console.log('Other error occurred');
    throw error;
  }
}

Type Definitions

Core utility types used throughout the package.

interface LiteralPart {
  type: 'literal';
  value: string;
}