or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

axes.mdbar-charts.mdevents.mdindex.mdinterpolation.mdline-charts.mdpie-charts.mdsvg-utilities.mdutils.md
tile.json

utils.mddocs/

Utility Functions

Chartist provides a comprehensive set of utility functions for data processing, mathematical operations, object manipulation, and functional programming patterns used throughout the charting system.

Capabilities

Data Processing Utilities

Functions for handling and processing chart data structures.

/**
 * Get high and low values from normalized data series
 * @param data - Array of normalized series data
 * @param options - Chart options that may contain bounds overrides
 * @param dimension - Optional axis dimension to extract values from
 * @returns Object with high and low values
 */
function getHighLow(
  data: NormalizedSeries[], 
  options: Options, 
  dimension?: AxisName
): { high: number; low: number };

/**
 * Normalize raw chart data into consistent format
 * @param data - Raw chart data (arrays or objects)
 * @param reverse - Whether to reverse the data order
 * @param multi - Enable multi-dimensional data or specify dimension
 * @param distributed - Enable distributed series handling
 * @returns Normalized data structure ready for rendering
 */
function normalizeData(
  data: Data, 
  reverse?: boolean, 
  multi?: boolean | AxisName, 
  distributed?: boolean
): NormalizedData;

/**
 * Get metadata from series data at specific index
 * @param seriesData - Series data (array or object)
 * @param index - Index to get metadata for
 * @returns Metadata object or undefined
 */
function getMetaData(
  seriesData: FlatSeriesValue | Series | SeriesObject, 
  index: number
): Meta | undefined;

/**
 * Check if value represents a data hole (null, undefined)
 * @param value - Value to check
 * @returns True if value is a data hole
 */
function isDataHoleValue(value: unknown): boolean;

/**
 * Check if value is an array of series objects
 * @param value - Value to check
 * @returns True if value is array of series
 */
function isArrayOfSeries(value: unknown): boolean;

/**
 * Check if value is multi-dimensional data object
 * @param value - Value to check
 * @returns True if value is multi-dimensional
 */
function isMultiValue(value: unknown): boolean;

/**
 * Extract value from multi-dimensional object by dimension
 * @param value - Multi-dimensional value or number
 * @param dimension - Dimension to extract (x or y)
 * @returns Extracted number value or undefined
 */
function getMultiValue(
  value: Multi | number | unknown, 
  dimension?: AxisName
): number | undefined;

/**
 * Split path coordinates into segments for rendering
 * @param pathCoordinates - Array of coordinate numbers
 * @param valueData - Array of value data with metadata
 * @param options - Optional segment splitting options
 * @returns Array of path segments
 */
function splitIntoSegments(
  pathCoordinates: number[], 
  valueData: SegmentData[], 
  options?: { increasingX?: boolean; fillHoles?: boolean }
): Segment[];

/**
 * Serialize data to string representation
 * @param data - Data to serialize
 * @returns Serialized string or null/undefined
 */
function serialize(
  data: number | string | object | null | undefined
): string | null | undefined;

/**
 * Deserialize string back to original data type
 * @param data - String data to deserialize
 * @returns Deserialized data of type T
 */
function deserialize<T>(data: string | null | undefined): T | null | undefined;

Mathematical Utilities

Mathematical functions for calculations and geometric operations.

/** Mathematical epsilon constant for precision comparisons */
const EPSILON: number;

/**
 * Calculate order of magnitude for a number
 * @param value - Number to calculate order of magnitude for
 * @returns Order of magnitude as integer
 */
function orderOfMagnitude(value: number): number;

/**
 * Project data length to pixel coordinates
 * @param axisLength - Length of axis in pixels
 * @param length - Data length to project
 * @param bounds - Axis bounds with min/max values
 * @returns Projected length in pixels
 */
function projectLength(
  axisLength: number, 
  length: number, 
  bounds: Bounds
): number;

/**
 * Round number with specified precision digits
 * @param value - Number to round
 * @param digits - Number of decimal places (default: uses global precision)
 * @returns Rounded number
 */
function roundWithPrecision(value: number, digits?: number): number;

/**
 * Find smallest prime factor using Pollard's rho algorithm
 * @param num - Number to find factor for
 * @returns Smallest prime factor
 */
function rho(num: number): number;

/**
 * Convert polar coordinates to cartesian coordinates
 * @param centerX - Center point X coordinate
 * @param centerY - Center point Y coordinate
 * @param radius - Distance from center
 * @param angleInDegrees - Angle in degrees (0 = top, 90 = right)
 * @returns Object with x and y cartesian coordinates
 */
function polarToCartesian(
  centerX: number, 
  centerY: number, 
  radius: number, 
  angleInDegrees: number
): { x: number; y: number };

/**
 * Calculate chart bounds from axis length and data range
 * @param axisLength - Length of axis in pixels
 * @param highLow - High and low values from data
 * @param scaleMinSpace - Minimum space between scale divisions
 * @param onlyInteger - Whether to use only integer values
 * @returns Calculated bounds object
 */
function getBounds(
  axisLength: number, 
  highLow: { high: number; low: number }, 
  scaleMinSpace: number, 
  onlyInteger?: boolean
): Bounds;

Type Checking Utilities

Functions for safe type checking and validation.

/**
 * Safely check if object has a specific property
 * @param target - Object to check
 * @param property - Property name to check for
 * @returns True if property exists on target
 */  
function safeHasProperty<T, K>(target: T, property: K): boolean;

/**
 * Check if value is numeric (number or numeric string)
 * @param value - Value to test
 * @returns True if value is numeric
 */
function isNumeric(value: unknown): boolean;

/**
 * Check if value is falsy but not zero
 * @param value - Value to test
 * @returns True if falsy but not zero
 */
function isFalseyButZero(value: unknown): boolean;

/**
 * Convert value to number safely
 * @param value - Value to convert
 * @returns Number if conversion successful, undefined otherwise
 */
function getNumberOrUndefined(value: unknown): number | undefined;

/**
 * Check if data structure is array of arrays
 * @param data - Data to check
 * @returns True if nested array structure
 */
function isArrayOfArrays(data: unknown): boolean;

Language Utilities

Functions for value conversion and string manipulation.

/**
 * Ensure numeric value has specified unit suffix
 * @param value - Value to process (number becomes string with unit)
 * @param unit - Unit string to append
 * @returns String with unit or original value if not number
 */
function ensureUnit<T>(value: T, unit: string): string | T;

/**
 * Convert input to quantity object with value and optional unit
 * @param input - Input value (number, string with unit, etc.)
 * @returns Object with numeric value and optional unit string
 */
function quantity<T>(input: T): { value: number; unit?: string };

/**
 * Convert number to alphabetic representation (0='a', 1='b', etc.)
 * @param n - Number to convert (0-25)
 * @returns Single letter string representation
 */
function alphaNumerate(n: number): string;

Object Manipulation

Functions for object extension and manipulation.

/**
 * Recursively extend target object with properties from source objects
 * @param target - Target object to extend
 * @returns Extended object (single argument returns clone)
 */
function extend<T>(target: T): T;
function extend<T, A>(target: T, a: A): T & A;
function extend<T, A, B>(target: T, a: A, b: B): T & A & B;
function extend<T, A, B, C>(target: T, a: A, b: B, c: C): T & A & B & C;
function extend<T, A, B, C, D>(target: T, a: A, b: B, c: C, d: D): T & A & B & C & D;

Array and Iteration Utilities

Functional programming utilities for array processing.

/**
 * Iterate over array with callback function
 * @param list - Array to iterate over
 * @param callback - Function called for each item
 * @param reverse - Whether to iterate in reverse order
 */
function each<T>(
  list: T[], 
  callback: (item: T, index: number, itemIndex: number) => void, 
  reverse?: boolean
): void;

/**
 * Create array filled with undefined values
 * @param length - Length of array to create
 * @returns Array of undefined values
 */
function times(length: number): undefined[];

/**
 * Create array using filler function
 * @param length - Length of array to create
 * @param filler - Function to generate values (receives index)
 * @returns Array of generated values
 */
function times<T>(length: number, filler: (index: number) => T): T[];

/**
 * Sum reducer function for arrays
 * @param previous - Previous sum value
 * @param current - Current number to add
 * @returns Sum of previous and current
 */
function sum(previous: number, current: number): number;

/**
 * Map function for multi-dimensional arrays
 * @param array - Array of arrays to process
 * @param callback - Function to call with spread arguments
 * @returns Array of callback results
 */
function serialMap<T, K>(array: T[][], callback: (...args: T[]) => K): K[];

/**
 * No-operation function that returns input unchanged
 * @param n - Input value
 * @returns Same input value
 */
function noop<T>(n: T): T;

Usage Examples:

import { 
  normalizeData, 
  getHighLow, 
  isNumeric, 
  extend, 
  times, 
  polarToCartesian 
} from "chartist";

// Data processing
const rawData = {
  labels: ['A', 'B', 'C'],
  series: [[1, 2, 3], [4, 5, 6]]
};

const normalized = normalizeData(rawData);
const bounds = getHighLow(normalized.series, {});

// Type checking
const value = "123";
if (isNumeric(value)) {
  console.log('Value is numeric');
}

// Object extension
const baseOptions = { width: 400 };
const fullOptions = extend(baseOptions, { height: 300 }, { showGrid: true });

// Array utilities
const indices = times(5, (i) => i * 2); // [0, 2, 4, 6, 8]
const total = [1, 2, 3, 4, 5].reduce(sum, 0); // 15

// Mathematical operations
const point = polarToCartesian(100, 100, 50, 45);
console.log(point); // { x: 135.35..., y: 64.64... }

Core Constants

Essential constants used throughout the library.

/** SVG and XML namespace definitions */
const namespaces: {
  svg: 'http://www.w3.org/2000/svg';
  xmlns: 'http://www.w3.org/2000/xmlns/';
  xhtml: 'http://www.w3.org/1999/xhtml';
  xlink: 'http://www.w3.org/1999/xlink';
  ct: 'http://gionkunz.github.com/chartist-js/ct';
};

/** Precision level for numerical calculations */
const precision: 8;

/** Character escaping map for safe HTML/XML attribute values */
const escapingMap: {
  '&': '&amp;';
  '<': '&lt;';
  '>': '&gt;';
  '"': '&quot;';
  "'": '&#039;';
};

Type Definitions

interface Bounds {
  min: number;
  max: number;
  step: number;
}

interface Multi {
  x?: number;
  y?: number;
}

interface SegmentData {
  value: number;
  meta: any;
}

interface Segment {
  pathCoordinates: number[];
  valueData: SegmentData[];
}

type AxisName = 'x' | 'y';

interface NormalizedSeries {
  data: number[];
  name?: string;
  className?: string;
  meta?: any;
}

interface NormalizedData {
  series: NormalizedSeries[];
  labels?: string[];
}