Documentation•Reference

HazelJS Numeric Package

npm downloads

@hazeljs/​numeric provides TypedArray-backed multidimensional arrays, broadcasting, linear algebra, and seeded random sampling for TypeScript.

Quick Reference

  • Purpose — Compute with multidimensional arrays and matrix routines.
  • When to use — Transform numeric data, solve linear systems, or generate reproducible simulations.
  • Key concepts — NDArray, dtype, shape, strides, and broadcasting.
  • Dependencies — Node.js 20 or later. The included backend runs in TypeScript with no npm runtime dependencies.
  • Common patterns — Wrap a TypedArray, apply broadcast operations, then pass the result to a matrix routine or Stats.
  • Common mistakes — Mutating a shared TypedArray buffer or assuming reductions use sample variance by default.

Purpose

Numeric provides a common representation for vectors and matrices so the same data can move between elementwise operations, linear algebra, and statistical routines.

Architecture

graph TD
  A["Nested arrays or TypedArrays"] --> B["NDArray with shape, dtype, and strides"]
  B --> C["Broadcast operations and reductions"]
  B --> D["Linear algebra"]
  D --> E["Backend selection for matmul, solve, and Cholesky"]

Advantages

  • Shared views can avoid copying data when wrapping a TypedArray or transposing a matrix.
  • Broadcasting applies a vector or scalar across an array without explicitly tiling the input.
  • Seeded generators let simulations reproduce the same input values.

Installation

The examples target HazelJS 2.2.0 and require Node.js 20 or later. Numeric uses a bundled TypeScript backend and has zero runtime dependencies.

npm install @hazeljs/​numeric@2.2.0

Quick Start

Work with arrays

import { array, fromTypedArray, matmul } from '@hazeljs/​numeric';

const matrix = array([
  [1, 2, 3],
  [4, 5, 6],
]);

const shifted = matrix.add(array([10, 20, 30]));
console.log(shifted.shape); /​/​ [2, 3]
console.log(shifted.get(1, 2)); /​/​ 36

const weights = fromTypedArray(new Float64Array([1, 0, 2]), { copy: false });
const scores = matmul(matrix, weights);
console.log(scores.get(0), scores.get(1)); /​/​ 7, 16

Broadcasting aligns dimensions from the right. Each aligned pair of dimensions must match or have a size of one. The length-three bias above broadcasts over both rows.

fromTypedArray with copy: false shares the underlying buffer. Transposes also share storage. Call .copy() when you need independent storage. The int64 and uint64 dtypes use BigInt TypedArrays. Float operations that need to convert a bigint reject conversions that would lose precision.

API Overview

Import linear algebra functions from @hazeljs/​numeric/​linalg or the package root.

APIUse
solve(a, b)Solve a square system with a vector or matrix of right-hand sides.
lu(a)Factor with row pivoting. The permutation maps rows of the factor product to original rows.
qr(a)Compute reduced QR with orthonormal columns in q.
cholesky(a)Compute a lower triangular factor of a symmetric positive-definite matrix.
svd(a)Compute reduced factors whose singular values are sorted in descending order.

The shipped implementations return float64 results. matmul, solve, and cholesky support backend selection with TypeScript as the fallback. Native BLAS, WASM SIMD, and WebGPU are planned.

Recipes

Port NumPy array operations

import * as np from '@hazeljs/​numeric';

const matrix = np.reshape(np.arange(1, 7), [2, -1]);
const totals = np.cumsum(matrix, { axis: 0 });
const columnOrder = matrix.argsort({ descending: true });
const filtered = np.where(matrix.gt(3), matrix, 0);

console.log(totals.toArray());       /​/​ [[1, 2, 3], [5, 7, 9]]
console.log(columnOrder.toArray());  /​/​ [[2, 1, 0], [2, 1, 0]]
console.log(filtered.toArray());     /​/​ [[0, 0, 0], [4, 5, 6]]
WorkflowNumeric API
Create from an array templatezeros_like(a), ones_like(a), full_like(a, value). They preserve the shape and dtype by default. The camelCase equivalents accept the same arguments.
Reshape or rearrange axesreshape(a, shape), ravel(a), transpose(a, axes?), squeeze(a, axis?), expand_dims, swapaxes, moveaxis, broadcast_to.
Order or deduplicate valuessort(a, { axis, descending }), argsort(a, { axis, descending }), unique(a).
Select or count valueswhere(mask, x, y) broadcasts its inputs. count_nonzero(a) returns a number across the whole array.
Scan or reduce valuescumsum, cumprod, prod, var, nansum, nanmean, nanmin, nanmax. The NaN reductions operate on the whole array.
Check numeric valuesisnan, isfinite, isinf, and isclose return boolean arrays. allclose returns one boolean.
Work directly with an array.T, .argsort(), .dot(), .matmul(), .prod(), .var(), .std(), .item(), .tolist().

reshape can infer one dimension marked -1. squeeze removes singleton dimensions and accepts a list of axes. .T returns a transpose view. Use .item() to extract a scalar from a one-element array and .tolist() to convert an array to nested JavaScript arrays or a scalar.

sort returns a sorted copy. argsort returns zero-based indices. Sorts are stable and put NaN last. Both functions default to the last axis and accept { axis: null } to flatten. unique returns sorted distinct values from the flattened input. cumsum and cumprod flatten unless you specify an axis.

Solve linear systems and factor matrices

import { array, matmul, multiply } from '@hazeljs/​numeric';
import { solve, svd } from '@hazeljs/​numeric/​linalg';

const a = array([[4, 2], [2, 3]]);
const x = solve(a, array([6, 5]));
console.log(x.get(0), x.get(1)); /​/​ 1, 1

const { u, s, vt } = svd(a);
const reconstructed = matmul(multiply(u, s), vt);

Sample and summarize

import { stats } from '@hazeljs/​numeric';
import { random } from '@hazeljs/​numeric/​random';

const sample = random.normal({ shape: [1_000], seed: 42 });
const summary = stats.describe(sample);

A seed makes sampling reproducible for simulations. Numeric's variance and stats.describe use population variance by default (ddof: 0). Use Stats for sample summaries, confidence intervals, and hypothesis tests. Stats accepts Numeric arrays as input.

Benchmarks

Numeric recorded the lowest median for 512 × 512 matrix multiplication among Numeric, math.js, and ml-matrix on an Apple M3 Max. The median was 73.0 ms, about 29% less time than ml-matrix. Numeric benchmark results

Run the Numeric suite from the HazelJS source checkout. It measures verified warm-run medians for vector addition, dot products, matrix multiplication, solves, and SVD against math.js and ml-matrix.

npm ci
npm run build -w @hazeljs/​numeric
cd benchmarks/​numeric
npm ci
npm start -- 512

Use the reported workload sizes when comparing results. The solve and SVD cases cap their matrix sizes independently of the CLI argument.