merge

Merges several matrices with a resolver, over the union of their keys.

import { Matrix } from "@teakit/matrix";

// Union keys (ascending), max row length, missing -> undefined.
Matrix.merge([{ a: [1, 2] }, { a: [10], b: [20] }], (values) => values);
// { a: [[1, 10], [2, undefined]], b: [[undefined, 20]] }

// "-" is passed to the resolver verbatim (not skipped).
const valueOrZero = (v: unknown): number => (typeof v === "number" ? v : 0);
Matrix.merge(
  [{ "2024": [10, 20] }, { "2024": [1] }, { "2024": ["-", 5] }],
  (values) => values.reduce((sum, v) => sum + valueOrZero(v), 0),
);
// { "2024": [11, 25] }

API Reference

Signature

Matrix.merge<TMatrices extends readonly [Matrix, ...Matrix[]], U>(
  matrices: TMatrices,
  resolver: MatrixMergeResolver<TMatrices, U>,
): Matrix<U, MatrixUnionKeys<TMatrices>>;
// resolver: (values, { key, rowIndex, colIndex }) => U

Parameters

ParameterTypeRequiredNotes
matrices[Matrix, ...Matrix[]]YesNon-empty array.
resolver(values, context) => UYesvalues[i] is each matrix's cell or undefined; context is { key, rowIndex, colIndex }.

Returns

A matrix keyed by the union of input keys (ascending). Each key's row length is the max across inputs; a matrix missing a key or column contributes undefined.

Throws

  • MATRIX_INVALID_MERGE_INPUT — non-array / empty matrices, or a non-function resolver.

Agent Contract

FieldValue
Kindstatic combinator
Canonical namemerge
AliasesNone
Mutates inputsNo
ReturnsMatrix<U, MatrixUnionKeys<TMatrices>>

Agent Notes

  • A cell value of "-" is passed to the resolver as "-"; handle it explicitly.
  • Missing key/column is undefined, distinct from a present "-".
  • To pair values into tuples instead of resolving, use zip.