From 7e1ba3ff90e870e39157f4297ee2be385bd9576b Mon Sep 17 00:00:00 2001 From: Sangwan Jeon Date: Sun, 16 Apr 2023 00:21:59 +0900 Subject: [PATCH] fix: bug on append --- package.json | 2 +- src/Flat.ts | 11 +++++++++++ test/append.test.ts | 16 ++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 84d232c..01920b5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "flattype", - "version": "0.3.0", + "version": "0.3.1", "description": "A simple library for creating flat types", "main": "dist/Flat.js", "module": "dist/Flat.js", diff --git a/src/Flat.ts b/src/Flat.ts index ce004b7..60647af 100644 --- a/src/Flat.ts +++ b/src/Flat.ts @@ -279,6 +279,17 @@ export default class Flat { throw new Error("Flat is not an array"); } + const subKeys = Object.keys(this.flat).filter( + (flatKey) => flatKey.startsWith(key) && flatKey !== key + ); + + if (subKeys.length === 0) { + const newKey = key === "" ? "0" : `${key}__0`; + this.set(newKey, value); + + return this; + } + const index = Object.keys(this.flat).filter( (flatKey) => flatKey.startsWith(key) && !flatKey.slice(key.length).includes("__") diff --git a/test/append.test.ts b/test/append.test.ts index 68ee5c2..c256f2d 100644 --- a/test/append.test.ts +++ b/test/append.test.ts @@ -12,12 +12,28 @@ describe("append(key: string, value: any) function", () => { }); }); + it("should append value by key on empty array", () => { + const flat = Flat.from({ + foo: [], + }); + + expect(flat.append("foo", "baz").getData()).toEqual({ + foo: ["baz"], + }); + }); + it("should append value by key on root", () => { const flat = Flat.from(["foo"]); expect(flat.append("", "baz").getData()).toEqual(["foo", "baz"]); }); + it("should append value by key on root when root is empty array", () => { + const flat = Flat.from([]); + + expect(flat.append("", "baz").getData()).toEqual(["baz"]); + }); + it("should throw an error when tried to append on non existing key", () => { const flat = Flat.from({ foo: "bar",