CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vega

A declarative visualization grammar for creating interactive data visualizations through JSON specifications.

Pending
Overview
Eval results
Files

utilities.mddocs/

Utility Functions

Vega's comprehensive utility library provides type checking, data manipulation, mathematical operations, string handling, configuration management, and general-purpose helper functions for visualization development.

Capabilities

Type Checking

Comprehensive type checking utilities for data validation.

/**
 * Check if value is an array
 * @param value - Value to test
 * @returns True if value is an array
 */
function isArray(value: any): value is any[];

/**
 * Check if value is a boolean
 * @param value - Value to test
 * @returns True if value is a boolean
 */
function isBoolean(value: any): value is boolean;

/**
 * Check if value is a Date object
 * @param value - Value to test
 * @returns True if value is a Date
 */
function isDate(value: any): value is Date;

/**
 * Check if value is a function
 * @param value - Value to test
 * @returns True if value is a function
 */
function isFunction(value: any): value is Function;

/**
 * Check if value is iterable
 * @param value - Value to test
 * @returns True if value is iterable
 */
function isIterable(value: any): boolean;

/**
 * Check if value is a number
 * @param value - Value to test
 * @returns True if value is a number
 */
function isNumber(value: any): value is number;

/**
 * Check if value is an object
 * @param value - Value to test
 * @returns True if value is an object
 */
function isObject(value: any): value is object;

/**
 * Check if value is a RegExp
 * @param value - Value to test
 * @returns True if value is a RegExp
 */
function isRegExp(value: any): value is RegExp;

/**
 * Check if value is a string
 * @param value - Value to test
 * @returns True if value is a string
 */
function isString(value: any): value is string;

Accessor Functions

Field accessor creation and manipulation utilities.

/**
 * Create field accessor function
 * @param field - Field name or accessor expression
 * @param name - Optional accessor name
 * @returns Field accessor function
 */
function accessor(field: string | Function, name?: string): Function;

/**
 * Get name of an accessor function
 * @param accessor - Accessor function
 * @returns Accessor name or field string
 */
function accessorName(accessor: Function): string;

/**
 * Get field names referenced by an accessor
 * @param accessor - Accessor function
 * @returns Array of field names
 */
function accessorFields(accessor: Function): string[];

/**
 * Create field accessor by name
 * @param name - Field name
 * @returns Field accessor function
 */
function field(name: string): (datum: any) => any;

/**
 * Create key function from field names
 * @param fields - Array of field names
 * @returns Key function that creates composite keys
 */
function key(fields: string[]): (datum: any) => string;

/**
 * Identity function - returns input unchanged
 * @param value - Input value
 * @returns Same value
 */
function identity<T>(value: T): T;

/**
 * Create ID accessor function
 * @returns Function that gets or generates unique IDs
 */
function id(): (datum: any) => any;

/**
 * Constant function that always returns zero
 * @returns Zero
 */
function zero(): number;

/**
 * Constant function that always returns one
 * @returns One
 */
function one(): number;

/**
 * Constant function that always returns true
 * @returns True
 */
function truthy(): boolean;

/**
 * Constant function that always returns false
 * @returns False
 */
function falsy(): boolean;

Data Manipulation

Core data structure operations and array utilities.

/**
 * Ensure value is an array
 * @param value - Value to arrayify
 * @returns Array containing the value or the value itself if already array
 */
function array<T>(value: T | T[]): T[];

/**
 * Compare two values for sorting
 * @param a - First value
 * @param b - Second value
 * @returns Comparison result (-1, 0, 1)
 */
function compare(a: any, b: any): number;

/**
 * Ascending comparison function
 * @param a - First value  
 * @param b - Second value
 * @returns Comparison result for ascending order
 */
function ascending(a: any, b: any): number;

/**
 * Extend target object with properties from source objects
 * @param target - Target object
 * @param sources - Source objects
 * @returns Extended target object
 */
function extend(target: any, ...sources: any[]): any;

/**
 * Merge objects recursively
 * @param target - Target object
 * @param source - Source object to merge
 * @returns Merged object
 */
function merge(target: any, source: any): any;

/**
 * Visit all items in nested arrays
 * @param array - Array to visit
 * @param visitor - Visitor function
 */
function visitArray(array: any[], visitor: (item: any, index: number) => void): void;

/**
 * Peek at the last item in an array
 * @param array - Array to peek
 * @returns Last item or undefined
 */
function peek<T>(array: T[]): T | undefined;

/**
 * Split accessor path into components
 * @param path - Dot-separated path string
 * @returns Array of path components
 */
function splitAccessPath(path: string): string[];

Mathematical Utilities

Mathematical operations and range utilities.

/**
 * Clamp range to specified bounds
 * @param range - Range tuple [min, max]
 * @param min - Minimum bound
 * @param max - Maximum bound
 * @returns Clamped range
 */
function clampRange(range: [number, number], min: number, max: number): [number, number];

/**
 * Calculate extent (min, max) of values
 * @param values - Array of values
 * @param accessor - Optional value accessor function
 * @returns Extent tuple [min, max]
 */
function extent(values: any[], accessor?: Function): [any, any];

/**
 * Calculate extent and return indices of min/max values
 * @param values - Array of values
 * @param accessor - Optional value accessor function
 * @returns Object with extent values and indices
 */
function extentIndex(values: any[], accessor?: Function): {
  extent: [any, any];
  minIndex: number;
  maxIndex: number;
};

/**
 * Check if value is within range
 * @param value - Value to test
 * @param range - Range tuple [min, max]
 * @param left - Left bound inclusion (default: true)
 * @param right - Right bound inclusion (default: true)
 * @returns True if value is in range
 */
function inrange(value: number, range: [number, number], left?: boolean, right?: boolean): boolean;

/**
 * Linear interpolation between two values
 * @param a - Start value
 * @param b - End value
 * @returns Interpolation function
 */
function lerp(a: number, b: number): (t: number) => number;

/**
 * Calculate span (max - min) of range
 * @param range - Range tuple [min, max]
 * @returns Span value
 */
function span(range: [number, number]): number;

String Operations

String manipulation and formatting utilities.

/**
 * Pad string to specified length
 * @param str - String to pad
 * @param length - Target length
 * @param character - Padding character (default: ' ')
 * @param align - Alignment ('left', 'right', 'center')
 * @returns Padded string
 */
function pad(str: string, length: number, character?: string, align?: 'left' | 'right' | 'center'): string;

/**
 * Repeat string specified number of times
 * @param str - String to repeat
 * @param count - Number of repetitions
 * @returns Repeated string
 */
function repeat(str: string, count: number): string;

/**
 * Convert value to string representation
 * @param value - Value to convert
 * @returns String representation
 */
function stringValue(value: any): string;

/**
 * Convert value to string with null safety
 * @param value - Value to convert
 * @returns String or empty string for null/undefined
 */
function toString(value: any): string;

/**
 * Truncate string to maximum length
 * @param str - String to truncate
 * @param length - Maximum length
 * @param align - Truncation alignment
 * @param ellipsis - Ellipsis string (default: '...')
 * @returns Truncated string
 */
function truncate(str: string, length: number, align?: 'left' | 'right' | 'center', ellipsis?: string): string;

Type Conversion

Type conversion utilities with safe defaults.

/**
 * Convert value to boolean
 * @param value - Value to convert
 * @returns Boolean value
 */
function toBoolean(value: any): boolean;

/**
 * Convert value to Date
 * @param value - Value to convert
 * @returns Date object or null
 */
function toDate(value: any): Date | null;

/**
 * Convert value to number
 * @param value - Value to convert
 * @returns Number value or NaN
 */
function toNumber(value: any): number;

/**
 * Convert array or iterable to Set
 * @param values - Values to convert
 * @returns Set containing the values
 */
function toSet<T>(values: Iterable<T>): Set<T>;

Utility Functions

General-purpose utility functions for common operations.

/**
 * Create constant function that returns the same value
 * @param value - Value to return
 * @returns Function that returns the constant value
 */
function constant<T>(value: T): () => T;

/**
 * Debounce function calls
 * @param func - Function to debounce
 * @param wait - Wait time in milliseconds
 * @param immediate - Execute immediately on first call
 * @returns Debounced function
 */
function debounce<T extends Function>(func: T, wait: number, immediate?: boolean): T;

/**
 * Throw an error with specified message
 * @param message - Error message
 * @throws Error with the specified message
 */
function error(message: string): never;

/**
 * Create fast map for object key-value operations
 * @returns Map-like object with fast access
 */
function fastmap(): FastMap;

/**
 * Flush pending operations (implementation specific)
 */
function flush(): void;

/**
 * Check if object has own property
 * @param object - Object to check
 * @param property - Property name
 * @returns True if object has own property
 */
function hasOwnProperty(object: any, property: string): boolean;

/**
 * Set up prototype inheritance
 * @param child - Child constructor
 * @param parent - Parent constructor
 */
function inherits(child: Function, parent: Function): void;

/**
 * Create LRU (Least Recently Used) cache
 * @param maxSize - Maximum cache size
 * @returns LRU cache instance
 */
function lruCache<K, V>(maxSize?: number): LRUCache<K, V>;

interface FastMap {
  has(key: string): boolean;
  get(key: string): any;
  set(key: string, value: any): FastMap;
  delete(key: string): boolean;
  clear(): void;
  size: number;
}

interface LRUCache<K, V> {
  has(key: K): boolean;
  get(key: K): V | undefined;
  set(key: K, value: V): LRUCache<K, V>;
  delete(key: K): boolean;
  clear(): void;
  size: number;
}

Configuration Management

Configuration merging and writing utilities.

/**
 * Merge configuration objects
 * @param configs - Configuration objects to merge
 * @returns Merged configuration
 */
function mergeConfig(...configs: any[]): any;

/**
 * Write configuration to storage or output
 * @param config - Configuration object
 * @param options - Write options
 */
function writeConfig(config: any, options?: WriteConfigOptions): void;

interface WriteConfigOptions {
  /** Output format */
  format?: 'json' | 'yaml' | 'js';
  
  /** Pretty print */
  pretty?: boolean;
  
  /** Output path */
  path?: string;
}

Logging System

Logging interface and level management.

/**
 * Logger interface for debugging and monitoring
 */
class logger {
  /**
   * Create new logger instance
   * @param level - Initial logging level
   */
  constructor(level?: number);
  
  /** Current logging level */
  level(): number;
  level(level: number): logger;
  
  /**
   * Log error message
   * @param message - Error message
   * @param data - Optional data
   */
  error(message: string, data?: any): void;
  
  /**
   * Log warning message
   * @param message - Warning message
   * @param data - Optional data
   */
  warn(message: string, data?: any): void;
  
  /**
   * Log info message
   * @param message - Info message
   * @param data - Optional data
   */
  info(message: string, data?: any): void;
  
  /**
   * Log debug message
   * @param message - Debug message
   * @param data - Optional data
   */
  debug(message: string, data?: any): void;
}

/** Logging level constants */
const None: 0;
const Error: 1;
const Warn: 2;
const Info: 3;
const Debug: 4;

Usage Examples

Type Checking

import { isArray, isString, isNumber, isObject } from "vega";

const data = [
  { name: "Alice", age: 25, scores: [85, 90, 92] },
  { name: "Bob", age: "30", scores: null },
  { name: null, age: 35, scores: [78, 82] }
];

data.forEach(person => {
  console.log('Name valid:', isString(person.name));
  console.log('Age is number:', isNumber(person.age));
  console.log('Scores is array:', isArray(person.scores));
  console.log('Person is object:', isObject(person));
});

Data Manipulation

import { extend, merge, array, extent, field } from "vega";

// Object extension
const base = { a: 1, b: 2 };
const extended = extend({}, base, { c: 3, d: 4 });
console.log(extended); // { a: 1, b: 2, c: 3, d: 4 }

// Array operations
const values = [5, 2, 8, 1, 9, 3];
const [min, max] = extent(values);
console.log(`Range: ${min} to ${max}`); // Range: 1 to 9

// Field accessors
const data = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 92 },
  { name: 'Carol', score: 78 }
];

const getName = field('name');
const getScore = field('score');

data.forEach(d => {
  console.log(`${getName(d)}: ${getScore(d)}`);
});

String Operations

import { pad, truncate, repeat } from "vega";

// Padding
console.log(pad('Hello', 10, '*', 'center')); // "**Hello***"
console.log(pad('123', 5, '0', 'left')); // "00123"

// Truncation
console.log(truncate('This is a long string', 10)); // "This is..."
console.log(truncate('Short', 10)); // "Short"

// Repetition
console.log(repeat('Ha', 3)); // "HaHaHa"
console.log(repeat('-', 20)); // "--------------------"

Mathematical Utilities

import { clampRange, inrange, lerp } from "vega";

// Range clamping
const range = clampRange([0, 100], 10, 90);
console.log(range); // [10, 90]

// Range checking
console.log(inrange(50, [0, 100])); // true
console.log(inrange(150, [0, 100])); // false

// Linear interpolation
const interpolator = lerp(0, 100);
console.log(interpolator(0.0)); // 0
console.log(interpolator(0.5)); // 50
console.log(interpolator(1.0)); // 100

Type Conversion

import { toBoolean, toNumber, toDate, toSet } from "vega";

// Safe type conversions
console.log(toBoolean('true')); // true
console.log(toBoolean('false')); // false
console.log(toBoolean(1)); // true
console.log(toBoolean(0)); // false

console.log(toNumber('42')); // 42
console.log(toNumber('invalid')); // NaN
console.log(toNumber(null)); // 0

const date = toDate('2023-06-15');
console.log(date); // Date object

const uniqueValues = toSet([1, 2, 2, 3, 3, 3]);
console.log(uniqueValues); // Set {1, 2, 3}

Utility Functions

import { constant, debounce, fastmap, lruCache } from "vega";

// Constant function
const getPI = constant(Math.PI);
console.log(getPI()); // 3.14159...

// Debounced function
const debouncedLog = debounce(console.log, 100);
debouncedLog('Message 1'); // Will be ignored
debouncedLog('Message 2'); // Will be ignored  
debouncedLog('Message 3'); // Will execute after 100ms

// Fast map
const map = fastmap();
map.set('key1', 'value1');
map.set('key2', 'value2');
console.log(map.get('key1')); // 'value1'
console.log(map.has('key3')); // false

// LRU Cache
const cache = lruCache(3);
cache.set('a', 1);
cache.set('b', 2);
cache.set('c', 3);
cache.set('d', 4); // 'a' will be evicted
console.log(cache.has('a')); // false
console.log(cache.has('d')); // true

Configuration Management

import { mergeConfig, writeConfig } from "vega";

const baseConfig = {
  view: { width: 400, height: 300 },
  mark: { fill: 'steelblue' }
};

const themeConfig = {
  view: { background: '#f5f5f5' },
  mark: { stroke: 'white', strokeWidth: 2 }
};

const userConfig = {
  view: { width: 600 },
  axis: { labelFontSize: 12 }
};

// Merge configurations
const finalConfig = mergeConfig(baseConfig, themeConfig, userConfig);
console.log(finalConfig);
// {
//   view: { width: 600, height: 300, background: '#f5f5f5' },
//   mark: { fill: 'steelblue', stroke: 'white', strokeWidth: 2 },
//   axis: { labelFontSize: 12 }
// }

// Write configuration
writeConfig(finalConfig, {
  format: 'json',
  pretty: true,
  path: 'config.json'
});

Logging

import { logger, None, Error, Warn, Info, Debug } from "vega";

// Create logger
const log = new logger(Info);

// Log messages at different levels
log.error('This is an error'); // Will show
log.warn('This is a warning'); // Will show
log.info('This is info'); // Will show
log.debug('This is debug'); // Will NOT show (level is Info)

// Change logging level
log.level(Debug);
log.debug('Now debug messages show'); // Will show

// Log with additional data
log.info('User action', {
  action: 'click',
  element: 'button',
  timestamp: Date.now()
});

Advanced Accessor Usage

import { accessor, accessorName, accessorFields, key } from "vega";

// Create complex accessor
const complexAccessor = accessor('d => d.nested.value * 2');
console.log(accessorName(complexAccessor)); // Function source or name

// Field names from accessor
const fields = accessorFields(complexAccessor);
console.log(fields); // ['nested.value']

// Composite key function
const keyFunc = key(['category', 'year']);
const data = [
  { category: 'A', year: 2020, value: 100 },
  { category: 'B', year: 2020, value: 200 },
  { category: 'A', year: 2021, value: 150 }
];

const grouped = new Map();
data.forEach(d => {
  const k = keyFunc(d);
  if (!grouped.has(k)) {
    grouped.set(k, []);
  }
  grouped.get(k).push(d);
});

console.log(Array.from(grouped.keys())); // ['A|2020', 'B|2020', 'A|2021']

Array Processing

import { visitArray, peek, extent, compare, ascending } from "vega";

const nestedData = [
  [1, [2, 3]], 
  [4, [5, [6, 7]]], 
  8
];

// Visit all nested items
visitArray(nestedData, (item, index) => {
  console.log(`Item ${index}:`, item);
});

// Peek at array
const numbers = [1, 2, 3, 4, 5];
console.log(peek(numbers)); // 5

// Sorting with comparisons
const unsorted = [3, 1, 4, 1, 5, 9, 2, 6];
const sorted = unsorted.slice().sort(ascending);
console.log(sorted); // [1, 1, 2, 3, 4, 5, 6, 9]

// Custom comparison
const people = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Carol', age: 35 }
];

people.sort((a, b) => compare(a.age, b.age));
console.log(people); // Sorted by age

Install with Tessl CLI

npx tessl i tessl/npm-vega

docs

data-loading.md

dataflow.md

events.md

expressions.md

index.md

parsing.md

scales.md

scenegraph.md

statistics.md

time.md

utilities.md

view.md

tile.json