Skip to content

Commit

Permalink
fix(collection): deundefined/null value when deleting array
Browse files Browse the repository at this point in the history
  • Loading branch information
alexberriman committed Aug 24, 2022
1 parent d3ad636 commit cd6a62f
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 6 deletions.
5 changes: 3 additions & 2 deletions src/collection/chain.ts
Expand Up @@ -225,13 +225,14 @@ export class Chain<
const mutations = flatten<PatchOperation>(
this.hashTable.nodes
.map((node) => {
const { data } = node;
const updated = isCallable<
(arg0: DataType) => DataType | Partial<DataType>
>(updateFnOrObject)
? updateFnOrObject(node.data)
? updateFnOrObject(data)
: updateFnOrObject;

return patchFn(node.data as unknown as object, updated, [
return patchFn(data as unknown as object, updated, [
node.hash,
node.$id,
]);
Expand Down
17 changes: 17 additions & 0 deletions src/collection/collection.test.ts
Expand Up @@ -402,6 +402,23 @@ describe("set", () => {
]);
expect(1).toBe(1);
});

it("removes an item from an array using set", () => {
const $ = new Collection([
{ color: "red", contents: ["apple", "orange", "banana"] },
]);

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

console.log($patch);

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

describe("replace", () => {
Expand Down
3 changes: 2 additions & 1 deletion src/collection/collection.ts
Expand Up @@ -72,7 +72,8 @@ export interface Chainable<
readonly nodes: HashTableItem<Index, Data>[];
readonly count: number;
readonly exists: boolean;
readonly or: any;
// @todo fix
readonly or: any; // eslint-disable-line
readonly chain: Chain<
Data,
IndexKeys,
Expand Down
2 changes: 2 additions & 0 deletions src/utils/collections/unset.test.ts
Expand Up @@ -4,4 +4,6 @@ test("unset", () => {
expect(unset({ a: { b: { c: "hello", d: {} } } }, "a.b.c")).toEqual({
a: { b: { d: {} } },
});

expect(unset(["banana", "apple", "pear"], "0")).toEqual(["apple", "pear"]);
});
9 changes: 6 additions & 3 deletions src/utils/collections/unset.ts
@@ -1,14 +1,17 @@
import { isNumeric } from "../types";
import { isArray, isNumeric } from "../types";

export function unset<T>(obj: T, path: string) {
const parts = path.split(".");

// eslint-disable-next-line @typescript-eslint/no-explicit-any
parts.reduce((o: any, key: string, index: number) => {
const isLast = index === parts.length - 1;

if (isLast) {
delete o[key];
if (isArray(o)) {
o.splice(Number(key), 1);
} else {
delete o[key];
}
} else if (!o[key]) {
o[key] = isNumeric(key) ? [] : {};
}
Expand Down

0 comments on commit cd6a62f

Please sign in to comment.