Skip to content

Commit

Permalink
Merge pull request #5 from diogofcunha/circular-dependecy-improve
Browse files Browse the repository at this point in the history
feat: 🎸 added dependent fields to circular dependency error
  • Loading branch information
diogofcunha authored Feb 26, 2024
2 parents 6e4cfa7 + cade2ba commit a215d6e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
24 changes: 20 additions & 4 deletions src/__tests__/editField.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createFormulaStore } from "..";
import { FormulaFieldCircularDependencyError } from "../errors";

describe("edit field", () => {
test("should fail if a listed dependency doesn`t exist", () => {
Expand Down Expand Up @@ -72,19 +73,34 @@ describe("edit field", () => {
calculate: calculateSpyFieldD
});

store.addField({
dependencies: ["d"],
id: "e",
value: 0,
calculate: () => 2
});

calculateSpyFieldD.mockClear();

expect(() =>
let error: null | FormulaFieldCircularDependencyError = null;

try {
store.editField({
dependencies: ["a", "b", "d"],
id: "d",
value: 0,
calculate: calculateSpyFieldD
})
).toThrowErrorMatchingInlineSnapshot(
`"Can't add field "d" due to circular dependency."`
});
} catch (ex) {
error = ex as FormulaFieldCircularDependencyError;
}

expect(error).toMatchInlineSnapshot(
`[Error: Can't add field "d" due to circular dependency.]`
);

expect(error?.dependentFields).toEqual(["e"]);

// Check if Field was removed.
expect(() =>
store.addField({
Expand Down
2 changes: 1 addition & 1 deletion src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class FormulaFieldNotFoundError extends Error {
}

export class FormulaFieldCircularDependencyError extends Error {
constructor(fieldId: string) {
constructor(fieldId: string, public readonly dependentFields: string[]) {
super(`Can't add field "${fieldId}" due to circular dependency.`);
}
}
Expand Down
8 changes: 7 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,15 @@ export function createFormulaStore({
try {
dependencyTree = fieldGraph.kahnTopologicalSort();
} catch (ex) {
const touchedNodes = getPossibleTouchedFieldsOnNodeChange(node);

touchedNodes.delete(node.id);

const dependentFields = [...touchedNodes];

removeField(node.id);

throw new FormulaFieldCircularDependencyError(node.id);
throw new FormulaFieldCircularDependencyError(node.id, dependentFields);
}

addedFields.set(node.id, node);
Expand Down

0 comments on commit a215d6e

Please sign in to comment.