From 22c1270a81061e95a45e55477a2bf0f713d1d358 Mon Sep 17 00:00:00 2001 From: Subin Siby Date: Fri, 21 Aug 2020 01:51:02 +0530 Subject: [PATCH] Add .appendToArray() #109, https://github.com/sindresorhus/electron-store/issues/52 --- source/index.ts | 19 +++++++++++++++++++ test/index.ts | 11 +++++++++++ 2 files changed, 30 insertions(+) diff --git a/source/index.ts b/source/index.ts index 8e29abb..d06cb97 100644 --- a/source/index.ts +++ b/source/index.ts @@ -223,6 +223,25 @@ class Conf = Record> implements I this.store = store; } + /** + Append an item or multiple items to an array + + @param {key|object} - You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a key to access nested properties. Or a hashmap of items to set at once. + @param value - Must be JSON serializable. Trying to set the type `undefined`, `function`, or `symbol` will result in a `TypeError`. + */ + appendToArray(key: Key, value: Required[Key]): void; + // This overload is used for dot-notation access. + appendToArray(key: Key, value: Required[Key]): void { + const list = this.get(key, [] as T[Key]); + + if (!Array.isArray(list)) { + throw new TypeError('Config param already set and is not array'); + } + + list.push(value); + this.set(key, list); + } + /** Check if an item exists. diff --git a/test/index.ts b/test/index.ts index bfee6a2..802cf88 100644 --- a/test/index.ts +++ b/test/index.ts @@ -99,6 +99,17 @@ test('.set() - invalid key', t => { }, {message: 'Expected `key` to be of type `string` or `object`, got number'}); }); +test('.appendToArray()', t => { + t.context.config.set('foo', [fixture]); + t.context.config.set('baz.boo', [fixture]); + t.context.config.appendToArray('foo', '🐴'); + t.context.config.appendToArray('baz.boo', '🐴'); + t.context.config.appendToArray('bar', '🐴'); // Will create new item with array + t.deepEqual(t.context.config.get('foo'), [fixture, '🐴']); + t.deepEqual(t.context.config.get('baz.boo'), [fixture, '🐴']); + t.deepEqual(t.context.config.get('bar'), ['🐴']); +}); + test('.has()', t => { t.context.config.set('foo', fixture); t.context.config.set('baz.boo', fixture);