vectyped
v1.2.1
Published
A fully typed minimal vector library
Maintainers
Readme
Vectyped
Lightweight, TypeScript-first vector and matrix utilities. The package provides Vector and Matrix
classes with a shared operation surface, full interoperability between the two, element-wise arithmetic,
linear algebra, and strict runtime guards for safe usage.
Overview
- Purpose: Provide small, well-tested
Vector/Matrixabstractions with arithmetic, geometric, and linear-algebra operations for N-dimensional vectors and R×C matrices. - Key features: Creation helpers, element-wise arithmetic, magnitude/normalization, dot/cross products,
rotation (2D/3D), transpose/matrix-product/inverse, Vector↔Matrix interoperability, conversion to/from
strings, and useful static presets (
RIGHT,LEFT,UP,DOWN).
Quick example
import { Matrix, Vector } from "vectyped";
const v = Vector.create(1, 2); // Vector<2>
v.add(3).multiply(0.5); // in-place arithmetic
const copy = v.copy(); // duplicate
const norm = v.getNorm(); // returns a normalized vector
console.log(v.toString(2)); // Vector<2>[...]
const m = Matrix.identity(2); // Matrix<2, 2>
const rotated = m.product(Matrix.rotation2D(Math.PI / 2)); // true matrix product
const transformed = v.transform(rotated); // Vector<2>, treated as a row vectorArithmetic methods on both classes also accept a plain number, another Vector/Matrix, or the raw
tuple/array representation directly — v.add([1, 2]) and m.multiply([[1, 0], [0, 1]]) work without
constructing an intermediate instance.
Vector API
Creation & presets
Vector.create(...components)— create a vector of any size.Vector.fill(size, value),Vector.zero(size),Vector.one(size),Vector.randomNormalised(size)— convenience methods.Vector.(RIGHT|LEFT|UP|DOWN)— common 2D unit vectors.Vector.parseString(str)— parse aVector<N>[...]formatted string.
Arithmetic & component-wise ops (mutating)
add(...),sub(...),multiply(...),divide(...),pow(...),mod(...),positiveMod(...)— accept a number, anotherVector, aMatrix<N,1>/Matrix<1,N>, or a raw tuple for component-wise operations.min(arg),max(arg)— component-wise min/max.
Interpolation & sums
lerp(t, arg)— linear interpolation towards a number orVector.sum()— sum of all components.
Rounding & sign helpers (mutating)
abs(),floor(),ceil(),round(digits?)— per-component numeric helpers.getSign()— returns a new vector of component signs.
Component min/max
getMin(),getMax()— scalar min/max across components.
Geometry & metrics
getSquaredMagnitude(),getMagnitude()— squared and Euclidean magnitude.getNorm(),normalise()— return a normalised vector or normalise in-place.setMagnitude(magnitude)— scale vector to a specific magnitude.dot(arg)— dot product with a number orVector.sqrDistTo(arg),distTo(arg)— squared distance and Euclidean distance to another vector/number.
2D-specific operations
getAngle()— returns angle in radians for 2D vectors.setAngle(angle)— set vector angle (keeps magnitude).rotate(pivot, angle)— rotate this 2D vector aboutpivotbyangle.
3D-specific operations
crossProduct(other)— cross product for 3D vectors.
Matrix interoperability
transform(matrix)— transform this vector by aMatrix<N, O>, treated as a row vector (v * M).outer(other)— outer product with anotherVector, returning aMatrix<N, M>.toMatrix(orientation?)— convert to a single-row (default) or single-columnMatrix.
Copying & mutation helpers
copy()— duplicate this vector.setHead(...components | [vector])— overwrite all components from an array or anotherVector(size must match).with(index, value)— return a new vector with the value atindexreplaced.concat(other)— concatenate components with anotherVector.
Accessors & indexing
size()— number of components.x(), y(), z(), w()— positional accessors (throw if the vector is too small).valueOf(i)— indexed access with bounds guard.toArray()— return components as an array.toString(digits?)— formattedVector<N>[...]string.
Functional & iteration
forEach(fn),map(fn),reduce(fn, initial?)— array-style helpers;mapreturns a newVector.every(fn),some(fn),includes(value)— predicates and membership.Symbol.iterator,Symbol.isConcatSpreadable, andSymbol.toStringTag— native iteration and concat behaviour.
Guards, comparisons & bounds
isSize(size)— runtime size guard.equals(other | components...)— deep equality by size and component values.inBounds(dimensions, positions = 0)— inclusive start / exclusive end bounds check.
Matrix API
Matrix<R, C> mirrors Vector's operations wherever a matrix analogue applies, plus linear algebra. A
MatrixArg<R,C> operand can be a number, another Matrix, a Vector<C>/Vector<R> (broadcast across rows
or columns respectively), or a raw tuple.
Creation
Matrix.create(...rows)— create a matrix from row arrays.Matrix.fill(rows, cols, value),Matrix.zero(rows, cols),Matrix.one(rows, cols),Matrix.randomNormalised(rows, cols)— convenience methods (randomNormalisedreturns a Frobenius-unit matrix).Matrix.identity(size)— square identity matrix.Matrix.parseString(str)— parse aMatrix<R,C>[[...],[...]]formatted string.Matrix.fromRows(...vectors),Matrix.fromColumns(...vectors)— build fromVectors.Matrix.fromVector(vector, orientation?)— build a single-row or single-column matrix from aVector.
Rotation constructors
Matrix.rotation2D(angle)— 2D rotation matrix.Matrix.rotation3D(axis, angle)— 3D rotation about an arbitrary axis, via Rodrigues' formula.Matrix.rotationInPlane(size, axis1, axis2, angle)— general N-dimensional rotation within the plane spanned by two axes.
Arithmetic & component-wise ops (mutating)
add(...),sub(...),multiply(...),divide(...),pow(...),mod(...),positiveMod(...)— cell-wise operations, mirroringVector.min(arg),max(arg),clamp(min, max)— cell-wise min/max/clamp.
Interpolation, sums, rounding & sign
lerp(t, arg),sum(),abs(),floor(),ceil(),round(digits?),getMin(),getMax(),getSign()— same semantics asVector, applied cell-wise across the whole matrix.
Structural
copy()— duplicate this matrix.rowSize(),columnSize()— dimensions.row(i),column(i)— get a row/column as aVector.setRow(i, row),setColumn(i, col)— overwrite a row/column with aVectoror broadcast number.valueOf(row, col)— indexed access with bounds guard.with(row, col, value)— return a new matrix with the cell replaced.toArray()— return cells as a 2D array.toString(digits?)— formattedMatrix<R,C>[[...],[...]]string.
Functional & iteration
forEach(fn),map(fn),reduce(fn, initial?)— array-style helpers over(value, row, col, matrix).every(fn),some(fn),includes(value)— predicates and membership.concatRows(other),concatColumns(other)— concatenate two matrices along an axis.Symbol.iterator(yields each row as aVector) andSymbol.toStringTag.
Guards & comparisons
isSize(rows, cols)— runtime shape guard.equals(other | rows...)— deep equality by shape and cell values.isSquare()— whether row and column counts match.
Linear algebra
transpose()— transpose this matrix.product(other)— true matrix product (as opposed tomultiply, which is cell-wise).transform(vector)— transform aVector<C>by this matrix (M * v).trace(),determinant(),inverse()— square matrices up to 4×4 only;inverse()throws on a singular matrix.
Interoperability
Vector and Matrix interoperate directly, without manual conversion:
import { Matrix, Vector } from "vectyped";
const v = Vector.create(1, 2, 3);
const m = Matrix.identity(3);
v.transform(m); // Vector<3> — v treated as a row vector, v * M
m.transform(v); // Vector<3> — M * v
v.outer(Vector.create(4, 5)); // Matrix<3, 2> outer product
v.toMatrix("column"); // Matrix<3, 1>
Matrix.fromVector(v, "row"); // Matrix<1, 3>
m.add(v); // Vector<C>/Vector<R> broadcasts across rows/columns
v.add([1, 1, 1]); // raw tuples work as arguments too