Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: added a transformAll function to id-tree.tsx (#4738)

Joaquin Coromina687b9ae76dfa
diff --git a/frontend/src/utils/__tests__/id-tree.test.ts b/frontend/src/utils/__tests__/id-tree.test.ts
index 2c0125b673..ca3462735e 100644
--- a/frontend/src/utils/__tests__/id-tree.test.ts
+++ b/frontend/src/utils/__tests__/id-tree.test.ts
@@ -747,6 +747,17 @@ describe("MultiColumn", () => {
expect(transformed.topLevelIds[1]).toEqual(["B2", "B1"]);
});
+ it("transforms all columns", () => {
+ const transformed = multiColumn.transformAll((tree) =>
+ tree.insertAtStart("NEW"),
+ );
+ expect(transformed.topLevelIds).toEqual([
+ ["NEW", "A1", "A2", "A3"],
+ ["NEW", "B1", "B2"],
+ ["NEW", "C1", "C2", "C3", "C4"],
+ ]);
+ });
+
it("inserts an id", () => {
const inserted = multiColumn.insertId("D1", columnIds[1], 1 as CellIndex);
expect(inserted.topLevelIds[1]).toEqual(["B1", "D1", "B2"]);
diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsx
index af3680e248..7ec9f3bfaa 100644
--- a/frontend/src/utils/id-tree.tsx
+++ b/frontend/src/utils/id-tree.tsx
@@ -884,4 +884,31 @@ export class MultiColumn<T> {
return new MultiColumn(newColumns);
}
+
+ /**
+ * Apply a transformation function to all columns
+ * @param fn The function to transform each column
+ * @returns A new MultiColumn if any changes were made, otherwise this
+ */
+ transformAll(
+ fn: (tree: CollapsibleTree<T>) => CollapsibleTree<T>,
+ ): MultiColumn<T> {
+ let didChange = false;
+
+ // Apply the transformation to all columns
+ const newColumns = this.columns.map((column) => {
+ const newColumn = fn(column);
+ if (!column.equals(newColumn)) {
+ didChange = true;
+ }
+ return newColumn;
+ });
+
+ // Avoid unnecessary re-renders if nothing changed
+ if (!didChange) {
+ return this;
+ }
+
+ return new MultiColumn(newColumns);
+ }
}