Skip to content

Commit

Permalink
refactor: unuse state of the list
Browse files Browse the repository at this point in the history
  • Loading branch information
noriaki committed Jun 24, 2020
1 parent ef27308 commit e930b2d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
21 changes: 19 additions & 2 deletions __tests__/hooks/useLinkedList.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import useLinkedList from '~/hooks/useLinkedList';
describe('useLinkedList hooks', () => {
it('set initial list', () => {
const { result } = renderHook(() => useLinkedList<number>([1, 10, 100]));
const { state, index, value } = result.current;
expect(state).toEqual([1, 10, 100]);
const { list, index, value } = result.current;
expect(list).toEqual([1, 10, 100]);
expect(index).toBe(0);
expect(value).toBe(1);
});
Expand Down Expand Up @@ -128,4 +128,21 @@ describe('useLinkedList hooks', () => {
expect(result.current.index).toBe(list.length - 1);
expect(result.current.value).toBe(100);
});

it('multiple lists', () => {
const numbers = [1, 10, 100];
const strings = ['a', 'b', 'c'];

const { result: num } = renderHook(() => useLinkedList<number>(numbers));
const { result: str } = renderHook(() => useLinkedList<string>(strings));

expect(num.current.index).toBe(0);
expect(str.current.index).toBe(0);

act(() => {
num.current.next();
});
expect(num.current.index).toBe(1);
expect(str.current.index).toBe(0);
});
});
7 changes: 3 additions & 4 deletions src/hooks/useLinkedList.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState, useCallback } from 'react';

type LinkedListHook<T> = {
state: T[];
list: T[];
index: number;
value: T;
next: () => void;
Expand All @@ -13,10 +13,9 @@ type LinkedListHook<T> = {
};

const useLinkedList = <T>(
initialLinkedList: T[] = [],
linkedList: T[] = [],
initialIndex = 0,
): LinkedListHook<T> => {
const [linkedList] = useState(initialLinkedList);
const [index, setIndex] = useState(initialIndex);

const next = useCallback(
Expand Down Expand Up @@ -54,7 +53,7 @@ const useLinkedList = <T>(
]);

return {
state: linkedList,
list: linkedList,
index,
value: linkedList[index],
next,
Expand Down

0 comments on commit e930b2d

Please sign in to comment.