Skip to content

Commit

Permalink
fix(set): updating an array
Browse files Browse the repository at this point in the history
  • Loading branch information
alexberriman committed Feb 17, 2023
1 parent 12d11fc commit e299867
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 5 deletions.
50 changes: 48 additions & 2 deletions src/collection/collection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,13 +408,59 @@ describe("set", () => {
{ color: "red", contents: ["apple", "orange", "banana"] },
]);

const $patch = $.get({ color: "red" })
$.get({ color: "red" })
.set({ contents: ["orange", "banana"] })
.commit();

console.log($patch);
expect($.get({ color: "red" }).data).toEqual({
color: "red",
contents: ["orange", "banana"],
});
});

it("updates an empty array", () => {
const $ = new Collection<{
color: string;
contents: string[];
animal: string;
}>(
[
{ color: "green", contents: ["apple"], animal: "gorilla" },
{ color: "red", contents: [], animal: "monkey" },
],
{ primaryKey: "color" }
);

$.get({ color: "red" })
.set({ contents: ["orange", "banana"], animal: "giraffe" })
.commit();

expect($.get({ color: "red" }).data).toEqual({
animal: "giraffe",
color: "red",
contents: ["orange", "banana"],
});
});

it("adds to an existing array", () => {
const $ = new Collection<{
color: string;
contents: string[];
animal: string;
}>(
[
{ color: "green", contents: ["apple"], animal: "gorilla" },
{ color: "red", contents: ["pea"], animal: "monkey" },
],
{ primaryKey: "color" }
);

$.get({ color: "red" })
.set({ contents: ["orange", "banana"], animal: "giraffe" })
.commit();

expect($.get({ color: "red" }).data).toEqual({
animal: "giraffe",
color: "red",
contents: ["orange", "banana"],
});
Expand Down
19 changes: 16 additions & 3 deletions src/data/hash-table/table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -432,10 +432,23 @@ export class HashTable<
const node = this.items[$id];

if ($id && node && path.length > 0) {
// adding a new attribute to an existing node
const attribute = path.join(".");
const original = cloneDeep(node.data);
set(this.items[$id].data as unknown as object, attribute, value);
const isAddToArrayOperation = path[path.length - 1] === "-";
const attribute = (isAddToArrayOperation ? path.slice(0, -1) : path).join(
"."
);
const { data } = this.items[$id];

if (isAddToArrayOperation) {
// add element to an array
const existing = dot(
data as Record<string, unknown>,
attribute
) as unknown[];
set(data, attribute, [...existing, value]);
} else {
set(data as unknown as object, attribute, value);
}

return {
operation: "addAttribute",
Expand Down

0 comments on commit e299867

Please sign in to comment.