Products

Formula Chain

Jspreadsheet uses a formula chain to track cell dependencies and automatically recalculate affected cells when values change. Each cell in the worksheet (records[y][x]) has a chain property - a JavaScript Map containing all cells that depend on it.

Overview

Consider these cells: A1 = 10, B1 = =A1, C1 = =B1 * 10

Chain structure:

  • A1's chain: Contains B1 (B1 depends on A1)
  • B1's chain: Contains C1 (C1 depends on B1)
  • C1's chain: Empty (no cells depend on C1)

When A1 changes to 20: A1 → B1 recalculates to 20 → C1 recalculates to 200

Example

Get All Dependencies

Use this function to find all cells affected by changing a specific cell:

function getChain(obj, x, y) {
  const result = [];
  const visited = new Set();

  function followChain(currentX, currentY) {
    // Check if the record exists at the coordinates
    if (!obj.records[currentY] || !obj.records[currentY][currentX]) {
      return;
    }

    const key = `${currentX},${currentY}`;
    // Prevent infinite loops by skipping visited cells
    if (visited.has(key)) {
      return;
    }

    visited.add(key);
    const record = obj.records[currentY][currentX];
    result.push(record);

    // Traverse all coordinates in the chain Map
    for (const [_, coords] of record.chain) {
      const [nextX, nextY] = coords;
      followChain(nextX, nextY);
    }
  }

  followChain(x, y);
  return result;
}

// Usage:
const dependentCells = getChain(worksheetInstance, 0, 0); // Get all cells dependent on A1

The function recursively follows the chain, prevents infinite loops with a visited set, and returns all affected cells.