From 7c20583995509b9715147bf2e24da82338ca78c6 Mon Sep 17 00:00:00 2001 From: Ward Oosterlijnck Date: Tue, 24 Sep 2019 10:19:28 +0200 Subject: [PATCH] useList allow pushing multiple items --- src/__tests__/useList.test.ts | 13 +++++++++++++ src/useList.ts | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/__tests__/useList.test.ts b/src/__tests__/useList.test.ts index 047e6e6840..f1e3e2dfe9 100644 --- a/src/__tests__/useList.test.ts +++ b/src/__tests__/useList.test.ts @@ -103,6 +103,19 @@ it('should push duplicated element at the end of the list', () => { expect(result.current[0]).not.toBe(initList); // checking immutability }); +it('should push multiple elements at the end of the list', () => { + const initList = [1, 2, 3]; + const { result } = setUp(initList); + const [, utils] = result.current; + + act(() => { + utils.push(4, 5, 6); + }); + + expect(result.current[0]).toEqual([1, 2, 3, 4, 5, 6]); + expect(result.current[0]).not.toBe(initList); // checking immutability +}); + it('should filter current list by provided function', () => { const initList = [1, -1, 2, -2, 3, -3]; const { result } = setUp(initList); diff --git a/src/useList.ts b/src/useList.ts index 5e292987aa..b54e72a165 100644 --- a/src/useList.ts +++ b/src/useList.ts @@ -5,7 +5,7 @@ export interface Actions { clear: () => void; updateAt: (index: number, item: T) => void; remove: (index: number) => void; - push: (item: T) => void; + push: (...items: T[]) => void; filter: (fn: (value: T) => boolean) => void; sort: (fn?: (a: T, b: T) => number) => void; } @@ -21,7 +21,7 @@ const useList = (initialList: T[] = []): [T[], Actions] => { updateAt: (index, entry) => set(currentList => [...currentList.slice(0, index), entry, ...currentList.slice(index + 1)]), remove: index => set(currentList => [...currentList.slice(0, index), ...currentList.slice(index + 1)]), - push: entry => set(currentList => [...currentList, entry]), + push: (...entry) => set(currentList => [...currentList, ...entry]), filter: fn => set(currentList => currentList.filter(fn)), sort: (fn?) => set(currentList => [...currentList].sort(fn)), },