Utility Functions
GridSheet provides several utility functions to help with common spreadsheet operations, coordinate conversions, data initialization, and type conversion.
Data Type Conversion
Section titled “Data Type Conversion”ensureNumber(value: any, options?: EnsureNumberOptions): number
Section titled “ensureNumber(value: any, options?: EnsureNumberOptions): number”Converts a value to a number with comprehensive type handling and error management.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
value | any | The value to convert to a number |
options | EnsureNumberOptions | Optional configuration for conversion behavior |
Options
Section titled “Options”| Option | Type | Description |
|---|---|---|
alternative | number | Default value to return if the input is undefined |
ignore | boolean | If true, returns 0 instead of throwing an error for invalid values |
Behavior
Section titled “Behavior”- Undefined values: Returns
alternativeif provided, otherwise throws error - Falsy values: Returns 0 (including
null,false,"") - Table instances: Extracts the first value using
stripTable - Date objects: Returns timestamp in milliseconds
- Percentage strings: Converts “50%” to 0.5
- String numbers: Parses numeric strings
- Invalid values: Throws
FormulaErrorwith “#VALUE!” code (unlessignoreis true)
Examples
Section titled “Examples”import { ensureNumber } from '@gridsheet/react-core';
// Basic conversionsensureNumber(42); // 42ensureNumber("123"); // 123ensureNumber("50%"); // 0.5ensureNumber(new Date()); // timestamp in milliseconds
// Falsy valuesensureNumber(null); // 0ensureNumber(""); // 0ensureNumber(false); // 0
// With optionsensureNumber(undefined, { alternative: 10 }); // 10ensureNumber("invalid", { ignore: true }); // 0
// Error casesensureNumber("invalid"); // throws FormulaError("#VALUE!")ensureNumber(undefined); // throws FormulaError("#VALUE!")ensureString(value: any): string
Section titled “ensureString(value: any): string”Converts a value to a string with special handling for different data types.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
value | any | The value to convert to a string |
Behavior
Section titled “Behavior”- Zero values: Returns “0” (preserves zero as string)
- Falsy values: Returns empty string (except 0)
- Table instances: Extracts the first value using
stripTable - Date objects: Formats using
FULLDATE_FORMAT_UTCformat - Other values: Uses
String()constructor
Examples
Section titled “Examples”import { ensureString } from '@gridsheet/react-core';
// Basic conversionsensureString(42); // "42"ensureString("hello"); // "hello"ensureString(0); // "0"
// Falsy valuesensureString(null); // ""ensureString(""); // ""ensureString(false); // "false"
// Date formattingensureString(new Date()); // "2024-01-15T10:30:00.000Z" (formatted)
// Table instancesensureString(tableInstance); // Extracts first value and convertsensureBoolean(value: any, options?: EnsureBooleanOptions): boolean
Section titled “ensureBoolean(value: any, options?: EnsureBooleanOptions): boolean”Converts a value to a boolean with strict string parsing and fallback handling.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
value | any | The value to convert to a boolean |
options | EnsureBooleanOptions | Optional configuration for conversion behavior |
Options
Section titled “Options”| Option | Type | Description |
|---|---|---|
alternative | boolean | Default value to return if the input is undefined |
ignore | boolean | If true, returns false instead of throwing an error for invalid string values |
Behavior
Section titled “Behavior”- Undefined values: Returns
alternativeif provided, otherwise throws error - Null values: Returns
false - Table instances: Extracts the first value using
stripTable - String values: Parses “true”/“false” (case-insensitive)
- Other values: Uses
Boolean()constructor
String Parsing
Section titled “String Parsing”Only the exact strings “true” and “false” (case-insensitive) are parsed as booleans. Any other string will throw an error (unless ignore is true).
Examples
Section titled “Examples”import { ensureBoolean } from '@gridsheet/react-core';
// Basic conversionsensureBoolean(true); // trueensureBoolean(false); // falseensureBoolean(1); // trueensureBoolean(0); // false
// String parsingensureBoolean("true"); // trueensureBoolean("TRUE"); // trueensureBoolean("false"); // falseensureBoolean("FALSE"); // false
// Falsy valuesensureBoolean(null); // falseensureBoolean(""); // false
// With optionsensureBoolean(undefined, { alternative: true }); // trueensureBoolean(undefined, { alternative: false }); // falseensureBoolean("invalid", { ignore: true }); // false
// Error casesensureBoolean("yes"); // throws FormulaError("#VALUE!")ensureBoolean("no"); // throws FormulaError("#VALUE!")ensureBoolean(undefined); // throws FormulaError("#VALUE!")Type Definitions
Section titled “Type Definitions”interface EnsureNumberOptions { alternative?: number; ignore?: boolean;}
interface EnsureBooleanOptions { alternative?: boolean; ignore?: boolean;}Data Initialization
Section titled “Data Initialization”buildInitialCells(config: InitialCellsConfig)
Section titled “buildInitialCells(config: InitialCellsConfig)”Creates a properly formatted initial cells configuration for the GridSheet component. This function accepts matrices at multiple base points and expands them into cell configurations.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
config | InitialCellsConfig | Configuration object with matrices, cells, ensured, and other options |
Configuration Options
Section titled “Configuration Options”| Option | Type | Description |
|---|---|---|
matrices | MatricesByAddress<any> | Matrices to be expanded at specific base points |
cells | CellsByAddressType | Individual cell data and configuration |
ensured | { numRows?: number; numCols?: number } | Minimum table dimensions |
flattenAs | keyof CellType | Property to flatten matrices into |
Matrix Expansion
Section titled “Matrix Expansion”The matrices object contains matrices at specific base points. Each matrix will be expanded starting from its base point:
import { buildInitialCells } from '@gridsheet/react-core';
const initialCells = buildInitialCells({ matrices: { // Matrix starting at A1 'A1': [ ['Name', 'Age', 'City'], ['John', 25, 'New York'], ['Jane', 30, 'Los Angeles'] ], // Matrix starting at D5 'D5': [ ['Product', 'Price', 'Stock'], ['Apple', 1.50, 100], ['Orange', 2.00, 75] ] }, cells: { // Individual cell configuration 'A': { width: 150 }, // Column A width '1': { height: 40 }, // Row 1 height 'B': { validation: { type: 'number', min: 0, max: 100 } } }, ensured: { numRows: 20, numCols: 10, },});
// Use with GridSheet component// <GridSheet initialCells={initialCells} />This will create:
- A table starting at A1 with the first matrix
- A table starting at D5 with the second matrix
- Column A width set to 150px
- Row 1 height set to 40px
- Column B with number validation (0-100)
buildInitialCellsFromOrigin(config: InitialCellsOriginConfig)
Section titled “buildInitialCellsFromOrigin(config: InitialCellsOriginConfig)”Creates initial cells configuration from matrix data, automatically generating column names.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
config | InitialCellsOriginConfig | Configuration with matrix data and options |
Configuration Options
Section titled “Configuration Options”| Option | Type | Description |
|---|---|---|
matrix | MatrixType | 2D array of data |
origin | Address | Starting address for the matrix |
cells | CellsByAddressType | Individual cell data and configuration |
ensured | { numRows?: number; numCols?: number } | Minimum table dimensions |
flattenAs | keyof CellType | Property to flatten matrix into |
Example
Section titled “Example”import { buildInitialCellsFromOrigin } from '@gridsheet/react-core';
const data = [ ['Name', 'Age', 'City'], ['John', 25, 'New York'], ['Jane', 30, 'Los Angeles'], ['Bob', 35, 'Chicago'],];
const initialCells = buildInitialCellsFromOrigin({ matrix: data, origin: 'A1', ensured: { numRows: 20, numCols: 10, },});
// Use with GridSheet component// <GridSheet initialCells={initialCells} />Coordinate Conversion
Section titled “Coordinate Conversion”Column Index to Letter
Section titled “Column Index to Letter”x2c(x: number): string
Section titled “x2c(x: number): string”Converts a column index (0-based) to a column letter.
import { x2c } from '@gridsheet/react-core';
console.log(x2c(0)); // 'A'console.log(x2c(25)); // 'Z'console.log(x2c(26)); // 'AA'console.log(x2c(27)); // 'AB'Letter to Column Index
Section titled “Letter to Column Index”c2x(c: string): number
Section titled “c2x(c: string): number”Converts a column letter to a column index (0-based).
import { c2x } from '@gridsheet/react-core';
console.log(c2x('A')); // 0console.log(c2x('Z')); // 25console.log(c2x('AA')); // 26console.log(c2x('AB')); // 27Row Index to Number
Section titled “Row Index to Number”y2r(y: number): number
Section titled “y2r(y: number): number”Converts a row index (0-based) to a row number (1-based).
import { y2r } from '@gridsheet/react-core';
console.log(y2r(0)); // 1console.log(y2r(9)); // 10console.log(y2r(99)); // 100Row Number to Index
Section titled “Row Number to Index”r2y(r: number): number
Section titled “r2y(r: number): number”Converts a row number (1-based) to a row index (0-based).
import { r2y } from '@gridsheet/react-core';
console.log(r2y(1)); // 0console.log(r2y(10)); // 9console.log(r2y(100)); // 99Point to Address
Section titled “Point to Address”p2a(p: PointType): string
Section titled “p2a(p: PointType): string”Converts a point object to a cell address string. The point coordinates are 1-based for cell addresses.
import { p2a } from '@gridsheet/react-core';
console.log(p2a({ y: 1, x: 1 })); // 'A1'console.log(p2a({ y: 10, x: 26 })); // 'Z10'console.log(p2a({ y: 100, x: 27 })); // 'AA100'Address to Point
Section titled “Address to Point”a2p(a: string): PointType
Section titled “a2p(a: string): PointType”Converts a cell address string to a point object. Returns 1-based coordinates for cell addresses.
import { a2p } from '@gridsheet/react-core';
console.log(a2p('A1')); // `{ y: 1, x: 1 }`console.log(a2p('Z10')); // `{ y: 10, x: 26 }`console.log(a2p('AA100')); // `{ y: 100, x: 27 }`Note:
- Cell addresses use 1-based coordinates (A1 =
{ y: 1, x: 1 }) - Column settings use
{ y: 0, x: x }format - Row settings use
{ y: y, x: 0 }format - The point
{ y: 0, x: 0 }is not used
Row Header Address
Section titled “Row Header Address”rh(y: number): string
Section titled “rh(y: number): string”Returns the row header cell address for the given row number by prepending 0. The row header cell is at column 0 of that row and is used to set row-level properties such as sortFixed, filterFixed, height, and style.
import { rh } from '@gridsheet/react-core';
rh(1) // '01'rh(6) // '06'
// multiple rows — use .map()[1, 2, 6].map(rh) // ['01', '02', '06']import { buildInitialCells, rh } from '@gridsheet/react-core';
buildInitialCells({ cells: { [rh(6)]: { sortFixed: true, filterFixed: true }, },})Column Header Address
Section titled “Column Header Address”ch(col: string | number): string
Section titled “ch(col: string | number): string”Returns the column header cell address for the given column letter or column index (1-based, same as point.x) by appending 0. The column header cell is at row 0 of that column and is used to set column-level properties such as width, label, and style.
import { ch } from '@gridsheet/react-core';
ch('A') // 'A0'ch(1) // 'A0' (column index 1 = column A)ch('B') // 'B0'ch(2) // 'B0'
// multiple columns — use .map()['A', 'B', 'C'].map(ch) // ['A0', 'B0', 'C0'][1, 2, 3].map(ch) // ['A0', 'B0', 'C0']import { buildInitialCells, ch } from '@gridsheet/react-core';
buildInitialCells({ cells: { [ch('A')]: { width: 150, label: 'Product' }, [ch('B')]: { width: 100, label: 'Q1' }, [ch(3)]: { width: 100, label: 'Q2' }, },})## Practical Examples
### Converting Between Formats
```tsximport { x2c, c2x, y2r, r2y, p2a, a2p } from '@gridsheet/react-core';
// Working with programmatic coordinatesconst colIndex = 5;const rowIndex = 10;
// Convert to addressconst address = p2a({ y: rowIndex, x: colIndex });console.log(address); // 'F10'
// Convert back to coordinatesconst point = a2p(address);console.log(point); // `{ y: 10, x: 5 }`
// Column operationsconst colLetter = x2c(colIndex);console.log(colLetter); // 'F'
const backToIndex = c2x(colLetter);console.log(backToIndex); // 5
// Row operationsconst rowNumber = y2r(rowIndex);console.log(rowNumber); // 10
const backToRowIndex = r2y(rowNumber);console.log(backToRowIndex); // 10Dynamic Cell Generation
Section titled “Dynamic Cell Generation”import { buildInitialCells, p2a } from '@gridsheet/react-core';
// Generate a multiplication tableconst generateMultiplicationTable = (size: number) => { const cells: any = {};
// Headers for (let i = 0; i <= size; i++) { cells[p2a({ y: 1, x: i + 1 })] = { value: i || '', style: { fontWeight: 'bold' } }; cells[p2a({ y: i + 1, x: 1 })] = { value: i || '', style: { fontWeight: 'bold' } }; }
// Multiplication values for (let row = 1; row <= size; row++) { for (let col = 1; col <= size; col++) { cells[p2a({ y: row + 1, x: col + 1 })] = { value: row * col }; } }
return buildInitialCells({ cells, ensured: { numRows: size + 1, numCols: size + 1 }, });};
const multiplicationTable = generateMultiplicationTable(10);Range Operations
Section titled “Range Operations”import { a2p, p2a } from '@gridsheet/react-core';
// Parse a rangeconst parseRange = (range: string) => { const [start, end] = range.split(':'); return { start: a2p(start), end: a2p(end), };};
// Generate all addresses in a rangeconst getAddressesInRange = (range: string) => { const { start, end } = parseRange(range); const addresses = [];
for (let row = start.row; row <= end.row; row++) { for (let col = start.col; col <= end.col; col++) { addresses.push(p2a({ row, col })); } }
return addresses;};
console.log(getAddressesInRange('A1:C3'));// ['A1', 'B1', 'C1', 'A2', 'B2', 'C2', 'A3', 'B3', 'C3']Type Definitions
Section titled “Type Definitions”interface PointType { y: number; x: number;}
interface InitialCellsConfig { matrices?: MatricesByAddress<any>; cells?: CellsByAddressType; ensured?: { numRows?: number; numCols?: number; }; flattenAs?: keyof CellType;}
interface InitialCellsOriginConfig { matrix?: MatrixType; origin?: Address; cells?: CellsByAddressType; ensured?: { numRows?: number; numCols?: number; }; flattenAs?: keyof CellType;}Performance Notes
Section titled “Performance Notes”- Coordinate conversion functions are optimized for performance
buildInitialCellsandbuildInitialCellsFromOriginshould be called during component initialization, not in render- For large datasets, consider using
buildInitialCellsFromOriginwith matrix data for better performance - Coordinate conversion functions are pure functions and can be safely memoized
Programmatic Control
Section titled “Programmatic Control”To control a GridSheet instance programmatically from outside the component, use sheetRef and storeRef. See Props Reference for the full API.