or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

array.mdcompat.mderror.mdfunction.mdindex.mdmath.mdobject.mdpredicate.mdpromise.mdstring.mdutil.md
tile.json

math.mddocs/

Mathematical Operations

Numerical computation utilities including statistical functions, random number generation, range utilities, and mathematical operations. All functions are optimized for accuracy and performance.

Capabilities

Statistical Functions

Functions for calculating common statistical measures from arrays of numbers.

/**
 * Calculates sum of array of numbers
 * @param nums - Array of numbers to sum
 * @returns Sum of all numbers
 */
function sum(nums: readonly number[]): number;

/**
 * Calculates sum using value selector function
 * @param arr - Array of items
 * @param getValue - Function to extract numeric value from each item
 * @returns Sum of extracted values
 */
function sumBy<T>(arr: readonly T[], getValue: (item: T) => number): number;

/**
 * Calculates arithmetic mean (average) of numbers
 * @param nums - Array of numbers
 * @returns Average of all numbers
 */
function mean(nums: readonly number[]): number;

/**
 * Calculates mean using value selector function
 * @param arr - Array of items  
 * @param getValue - Function to extract numeric value from each item
 * @returns Average of extracted values
 */
function meanBy<T>(arr: readonly T[], getValue: (item: T) => number): number;

/**
 * Finds median value in array of numbers
 * @param nums - Array of numbers
 * @returns Median value
 */
function median(nums: readonly number[]): number;

/**
 * Finds median using value selector function
 * @param arr - Array of items
 * @param getValue - Function to extract numeric value from each item
 * @returns Median of extracted values
 */
function medianBy<T>(arr: readonly T[], getValue: (item: T) => number): number;

Usage Examples:

import { sum, sumBy, mean, meanBy, median, medianBy } from 'es-toolkit/math';

// Basic statistical calculations
const scores = [85, 92, 78, 96, 88, 94, 82];

console.log(sum(scores));    // 615
console.log(mean(scores));   // 87.857...
console.log(median(scores)); // 88

// Working with objects
const students = [
  { name: 'Alice', grade: 92, age: 20 },
  { name: 'Bob', grade: 85, age: 19 },
  { name: 'Charlie', grade: 88, age: 21 },
  { name: 'Diana', grade: 95, age: 20 }
];

const totalGrades = sumBy(students, student => student.grade);
console.log(totalGrades); // 360

const averageGrade = meanBy(students, student => student.grade);
console.log(averageGrade); // 90

const medianAge = medianBy(students, student => student.age);
console.log(medianAge); // 20

// Sales data analysis
const salesData = [
  { product: 'Laptop', revenue: 50000, units: 25 },
  { product: 'Phone', revenue: 30000, units: 60 },
  { product: 'Tablet', revenue: 15000, units: 30 }
];

const totalRevenue = sumBy(salesData, item => item.revenue);
const averageRevenue = meanBy(salesData, item => item.revenue);
const medianUnits = medianBy(salesData, item => item.units);

console.log({ totalRevenue, averageRevenue, medianUnits });
// { totalRevenue: 95000, averageRevenue: 31666.67, medianUnits: 30 }

Number Utilities

Functions for working with individual numbers including clamping, range checking, and rounding.

/**
 * Clamps number within bounds
 * @param value - Number to clamp
 * @param bound1 - First bound
 * @param bound2 - Second bound (optional, treated as upper bound)
 * @returns Number clamped within bounds
 */
function clamp(value: number, bound1: number, bound2?: number): number;

/**
 * Checks if number is within range
 * @param value - Number to check
 * @param min - Minimum value (inclusive)
 * @param max - Maximum value (exclusive)
 * @returns True if value is within range
 */
function inRange(value: number, min: number, max: number): boolean;

/**
 * Rounds number to specified precision
 * @param number - Number to round
 * @param precision - Number of decimal places (default: 0)
 * @returns Rounded number
 */
function round(number: number, precision?: number): number;

Usage Examples:

import { clamp, inRange, round } from 'es-toolkit/math';

// Clamping values
console.log(clamp(10, 5, 15));  // 10 (within bounds)
console.log(clamp(3, 5, 15));   // 5 (below min)
console.log(clamp(20, 5, 15));  // 15 (above max)

// Single bound clamping (0 to bound)
console.log(clamp(10, 15));     // 10 (within 0-15)
console.log(clamp(-5, 15));     // 0 (clamped to 0)
console.log(clamp(20, 15));     // 15 (clamped to upper)

// Range checking
console.log(inRange(5, 0, 10));   // true
console.log(inRange(10, 0, 10));  // false (max is exclusive)
console.log(inRange(-1, 0, 10));  // false

// Progress bar example
function updateProgress(value: number): string {
  const percentage = clamp(value, 0, 100);
  return `Progress: ${percentage}%`;
}

console.log(updateProgress(150)); // "Progress: 100%"
console.log(updateProgress(-10)); // "Progress: 0%"

// Rounding with precision
console.log(round(3.14159));      // 3
console.log(round(3.14159, 2));   // 3.14
console.log(round(3.14159, 4));   // 3.1416
console.log(round(1234.5678, -2)); // 1200 (round to hundreds)

// Financial calculations
const price = 29.999;
const taxRate = 0.0825;
const total = price * (1 + taxRate);

console.log(round(total, 2)); // 32.47 (proper currency formatting)

Random Number Generation

Functions for generating random numbers with various constraints and distributions.

/**
 * Generates random floating-point number
 * @param minimum - Minimum value (inclusive)
 * @param maximum - Maximum value (exclusive) 
 * @returns Random number in range [minimum, maximum)
 */
function random(minimum: number, maximum?: number): number;

/**
 * Generates random integer
 * @param minimum - Minimum value (inclusive)
 * @param maximum - Maximum value (exclusive)
 * @returns Random integer in range [minimum, maximum)
 */
function randomInt(minimum: number, maximum?: number): number;

Usage Examples:

import { random, randomInt } from 'es-toolkit/math';

// Random floating-point numbers
console.log(random(0, 1));      // 0.123... (between 0 and 1)
console.log(random(10, 20));    // 15.678... (between 10 and 20)
console.log(random(100));       // 67.891... (between 0 and 100)

// Random integers
console.log(randomInt(1, 7));   // 1, 2, 3, 4, 5, or 6 (dice roll)
console.log(randomInt(0, 2));   // 0 or 1 (coin flip)
console.log(randomInt(10));     // 0-9 (single digit)

// Practical examples
function generatePassword(length: number): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let password = '';
  
  for (let i = 0; i < length; i++) {
    const randomIndex = randomInt(0, chars.length);
    password += chars[randomIndex];
  }
  
  return password;
}

function simulateDelay(): number {
  // Random delay between 100ms and 2000ms
  return randomInt(100, 2000);
}

function pickRandomItem<T>(array: T[]): T {
  const randomIndex = randomInt(0, array.length);
  return array[randomIndex];
}

const fruits = ['apple', 'banana', 'orange', 'grape'];
console.log(pickRandomItem(fruits)); // Random fruit

// Random color generator
function randomColor(): string {
  const r = randomInt(0, 256);
  const g = randomInt(0, 256);
  const b = randomInt(0, 256);
  return `rgb(${r}, ${g}, ${b})`;
}

console.log(randomColor()); // "rgb(123, 45, 200)"

Range Generation

Functions for creating sequences of numbers with various patterns and step sizes.

/**
 * Creates array of numbers in specified range
 * @param start - Starting number
 * @param end - Ending number (exclusive)
 * @param step - Step size (default: 1)
 * @returns Array of numbers in range
 */
function range(start: number, end?: number, step?: number): number[];

/**
 * Creates array of numbers in reverse order
 * @param start - Starting number
 * @param end - Ending number (exclusive)
 * @param step - Step size (default: 1)
 * @returns Array of numbers in reverse range
 */
function rangeRight(start: number, end?: number, step?: number): number[];

Usage Examples:

import { range, rangeRight } from 'es-toolkit/math';

// Basic ranges
console.log(range(5));           // [0, 1, 2, 3, 4]
console.log(range(1, 6));        // [1, 2, 3, 4, 5]  
console.log(range(0, 10, 2));    // [0, 2, 4, 6, 8]
console.log(range(10, 0, -2));   // [10, 8, 6, 4, 2]

// Reverse ranges
console.log(rangeRight(5));      // [4, 3, 2, 1, 0]
console.log(rangeRight(1, 6));   // [5, 4, 3, 2, 1]

// Practical applications
function createPagination(currentPage: number, totalPages: number): number[] {
  const start = Math.max(1, currentPage - 2);
  const end = Math.min(totalPages, currentPage + 2) + 1;
  return range(start, end);
}

console.log(createPagination(5, 10)); // [3, 4, 5, 6, 7]

function generateTimeSlots(startHour: number, endHour: number): string[] {
  return range(startHour, endHour).map(hour => {
    const period = hour >= 12 ? 'PM' : 'AM';
    const displayHour = hour > 12 ? hour - 12 : hour === 0 ? 12 : hour;
    return `${displayHour}:00 ${period}`;
  });
}

console.log(generateTimeSlots(9, 17));
// ['9:00 AM', '10:00 AM', '11:00 AM', '12:00 PM', '1:00 PM', ...]

// Create chart data points
function generateDataPoints(min: number, max: number, points: number) {
  const step = (max - min) / (points - 1);
  return range(points).map(i => ({
    x: min + (i * step),
    y: Math.sin(min + (i * step)) // Example function
  }));
}

const chartData = generateDataPoints(0, Math.PI * 2, 50);

// Array indices for iteration
const indices = range(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
indices.forEach(i => {
  console.log(`Processing item ${i}`);
});

// Decimal ranges
console.log(range(0, 1, 0.1)); // [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

// Year ranges for dropdowns
const currentYear = new Date().getFullYear();
const yearOptions = range(currentYear - 10, currentYear + 5);
console.log(yearOptions); // [2014, 2015, ..., 2029] (example for 2024)

Advanced Usage Patterns

Data Analysis Pipeline

Combine multiple math functions for comprehensive data analysis:

import { sum, mean, median, clamp } from 'es-toolkit/math';

function analyzeDataset(data: number[]) {
  // Remove outliers by clamping to reasonable bounds
  const q1 = median(data.slice().sort().slice(0, Math.floor(data.length / 4)));
  const q3 = median(data.slice().sort().slice(Math.ceil(data.length * 3 / 4)));
  const iqr = q3 - q1;
  const lowerBound = q1 - 1.5 * iqr;
  const upperBound = q3 + 1.5 * iqr;
  
  const cleanedData = data.map(value => clamp(value, lowerBound, upperBound));
  
  return {
    total: sum(cleanedData),
    average: mean(cleanedData),
    median: median(cleanedData),
    count: cleanedData.length
  };
}

Random Sampling and Simulation

import { random, randomInt, range } from 'es-toolkit/math';

function monteCarloSimulation(iterations: number): number {
  let insideCircle = 0;
  
  for (let i = 0; i < iterations; i++) {
    const x = random(-1, 1);
    const y = random(-1, 1);
    
    if (x * x + y * y <= 1) {
      insideCircle++;
    }
  }
  
  return (insideCircle / iterations) * 4; // Estimate of π
}

console.log(monteCarloSimulation(100000)); // Approximation of π

Financial Calculations

import { sum, round, range } from 'es-toolkit/math';

function calculateCompoundInterest(
  principal: number,
  rate: number,
  time: number,
  frequency: number = 12
): { values: number[], total: number } {
  const monthlyRate = rate / frequency;
  const periods = range(time * frequency + 1);
  
  const values = periods.map(period => {
    const amount = principal * Math.pow(1 + monthlyRate, period);
    return round(amount, 2);
  });
  
  return {
    values,
    total: values[values.length - 1]
  };
}

const investment = calculateCompoundInterest(10000, 0.07, 5);
console.log(`Investment grows to: $${investment.total}`);

Performance Characteristics

  • Numerical Stability: Algorithms designed to minimize floating-point errors
  • Memory Efficient: Optimized for large datasets without excessive memory allocation
  • Fast Execution: Highly optimized mathematical operations
  • Precision Handling: Proper rounding and precision management for financial calculations
  • Edge Case Handling: Robust handling of edge cases like empty arrays, NaN, and infinity

Mathematical Accuracy

ES-Toolkit's math functions handle common floating-point precision issues:

import { round, sum } from 'es-toolkit/math';

// Floating-point precision issues
console.log(0.1 + 0.2);                    // 0.30000000000000004
console.log(round(0.1 + 0.2, 10));         // 0.3

// Accurate summation for financial data
const decimals = [0.1, 0.2, 0.3];
console.log(sum(decimals));                 // Properly handled precision
console.log(round(sum(decimals), 2));      // 0.6