Bookmark this: tool.io/matrix/as-table/source-code
Matrix as Table Source Code
Browse the implementation files for Matrix as Table.tool.ts typescript
import { matrixAsTable as formatPortableMatrixAsTable } from '@tool.io/tools/matrix/as-table';
export type NumericTable = {
kind: 'tool.io/table';
rows: number[][];
schema: {
fields: {
dataType: { bits: 64; kind: 'float' };
id: string;
label: string;
nullable: false;
}[];
};
version: 1;
};
export const parseNumericTable = (
input: unknown
): NumericTable | null => {
let value = input;
if (typeof input === 'string') {
try {
value = JSON.parse(input);
} catch {
return null;
}
}
if (
typeof value !== 'object' ||
value === null ||
Array.isArray(value)
)
return null;
const table = value as Partial<NumericTable>;
if (
table.kind !== 'tool.io/table' ||
table.version !== 1 ||
!Array.isArray(table.schema?.fields) ||
!Array.isArray(table.rows) ||
!table.schema.fields.every(
(field) =>
typeof field === 'object' &&
field !== null &&
typeof field.id === 'string' &&
typeof field.label === 'string' &&
field.nullable === false &&
field.dataType?.kind === 'float' &&
field.dataType.bits === 64
) ||
!table.rows.every(
(row) =>
Array.isArray(row) &&
row.length === table.schema?.fields.length &&
row.every(
(cell) =>
typeof cell === 'number' && Number.isFinite(cell)
)
)
)
return null;
return table as NumericTable;
};
export const matrixAsTable = (
input: unknown
): NumericTable | null => {
const table = parseNumericTable(
formatPortableMatrixAsTable(input)
);
return table === null
? null
: {
kind: table.kind,
rows: table.rows.map((row) => [...row]),
schema: {
fields: table.schema.fields.map((field) => ({
...field,
dataType: { ...field.dataType }
}))
},
version: table.version
};
};
export const formatMatrixAsTable = (input: unknown): string => {
const table = matrixAsTable(input);
return table === null ? '' : JSON.stringify(table, null, 2);
};
export const Tool: TypeTool = {
name: 'Matrix as Table',
slug: 'matrix/as-table',
intro:
'Convert a numeric matrix into a structured, versioned table value.',
tool: formatMatrixAsTable,
i: [
{
example: '[[1,2],[3,4]]',
label: 'Matrix',
placeholder: 'Enter a matrix',
render: 'textarea',
type: 'text'
}
],
o: [
{
example: '{\n "kind": "tool.io/table",\n ...\n}',
label: 'Table',
placeholder: 'Structured table will appear here...',
render: 'textarea',
type: 'text'
}
],
alternative: [
{ title: 'Numeric Matrix Parser', url: '/parse/matrix' }
]
};
export default Tool;
Description
Browse the implementation files for Matrix as Table.