Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useCallback, useReducer } from "react";
- interface IState<T> {
- index: number;
- list: T[];
- }
- const initialState: IState<any> = {
- index: -1,
- list: []
- }
- export function useCircularQueue<T>() { // to-think: maybe first element of queue?
- const [state, dispatchState] = useReducer((current: IState<T>, action: any) => {
- const { index, list } = current;
- switch(action.type) {
- case 'pop':
- if (list.length === 1) {
- current = {
- ...initialState
- };
- } else if (list.length === 0) {
- console.error('useCircularQueue error: array\'s already empty.');
- } else {
- current = {
- ...current,
- index: (index === (list.length - 1)) ? index - 1 : index,
- list: list.filter((e: T, eIndex) => eIndex !== index)
- };
- }
- break;
- case 'push':
- current = {
- ...current,
- index: index === -1 ? 0 : index,
- list: [ ...list, action.payload ]
- };
- break;
- case 'next':
- if (list.length === 0) {
- console.error('useCircularQueue error: array\'s still empty.');
- } else {
- current = {
- ...current,
- index: index === list.length - 1 ? 0 : index + 1
- };
- }
- break;
- default:
- current = {
- ...current
- };
- break;
- }
- return current;
- }, initialState);
- const pop = useCallback(() => {
- alert();
- dispatchState({ type: 'pop' });
- }, []);
- const push = useCallback((newItem: T) => {
- dispatchState({ type: 'push', payload: newItem });
- }, []);
- const next = useCallback(() => {
- dispatchState({ type: 'next' });
- }, []);
- const current = (state.index === -1) ? null : state.list[state.index];
- return { value: current, index: state.index, list: state.list, push, pop, next };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement