Skip to content

Commit

Permalink
update highest id check
Browse files Browse the repository at this point in the history
  • Loading branch information
timarney committed Nov 27, 2024
1 parent 78475b8 commit 5a0b32c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
39 changes: 39 additions & 0 deletions lib/store/__tests__/generateElementId.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,43 @@ describe("generateElementId", () => {
expect(result.current.form.lastGeneratedElementId).toBe(6);

});

it("gets highest element id", async () => {
const result = createStore();

const element = {
id: 201,
type: FormElementTypes.textField,
properties: {
titleEn: "question 201 en",
titleFr: "question 201 fr",
choices: [],
validation: { required: false },
descriptionEn: "description en",
descriptionFr: "descrption fr",
},
};

result.current.form = {
titleEn: "Title en",
titleFr: "Title fr",
elements: [
defaultElements[0],
defaultElements[1],
element, // <- Out of sequence and high id for testing purposes
defaultElements[2],
defaultElements[10] // <-- This is purposely undefined - to test check for element.id
],
layout: []
};

// Ensure we have a default form to work with
expect(result.current.form.titleEn).toBe("Title en");
expect(result.current.form.titleFr).toBe("Title fr");

// Check that the highest element id is 201
expect(result.current.getHighestElementId()).toBe(201);

});

});
9 changes: 7 additions & 2 deletions lib/store/useTemplateStore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -524,8 +524,13 @@ const createTemplateStore = (initProps?: Partial<InitialTemplateStoreProps>) =>
});
},
getHighestElementId: () => {
const currentIds = get().form.elements.map((element) => element.id);
return currentIds.length > 0 ? Math.max(...currentIds) : 0;
const validIds = get()
.form.elements.filter(
(element) => element && typeof element.id === "number" && !isNaN(element.id)
)
.map((element) => Number(element.id));

return validIds.length > 0 ? Math.max(...validIds) : 0;
},
generateElementId: () => {
set((state) => {
Expand Down

0 comments on commit 5a0b32c

Please sign in to comment.