Advertisement
cirossmonteiro

useCircularQueue

Sep 19th, 2022 (edited)
834
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useCallback, useReducer } from "react";
  2.  
  3. interface IState<T> {
  4.   index: number;
  5.   list: T[];
  6. }
  7.  
  8. const initialState: IState<any> = {
  9.   index: -1,
  10.   list: []
  11. }
  12.  
  13. export function useCircularQueue<T>() { // to-think: maybe first element of queue?
  14.  
  15.   const [state, dispatchState] = useReducer((current: IState<T>, action: any) => {
  16.     const { index, list } = current;
  17.     switch(action.type) {
  18.  
  19.       case 'pop':
  20.         if (list.length === 1) {
  21.           current = {
  22.             ...initialState
  23.           };
  24.         } else if (list.length === 0) {
  25.           console.error('useCircularQueue error: array\'s already empty.');
  26.         } else {
  27.           current = {
  28.             ...current,
  29.             index: (index === (list.length - 1)) ? index - 1 : index,
  30.             list: list.filter((e: T, eIndex) => eIndex !== index)
  31.           };
  32.         }
  33.         break;
  34.  
  35.       case 'push':
  36.         current = {
  37.           ...current,
  38.           index: index === -1 ? 0 : index,
  39.           list: [ ...list, action.payload ]
  40.         };
  41.         break;
  42.  
  43.       case 'next':
  44.         if (list.length === 0) {
  45.           console.error('useCircularQueue error: array\'s still empty.');
  46.         } else {
  47.           current = {
  48.             ...current,
  49.             index: index === list.length - 1 ? 0 : index + 1
  50.           };
  51.         }
  52.         break;
  53.      
  54.       default:
  55.         current = {
  56.           ...current
  57.         };
  58.         break;
  59.     }
  60.     return current;
  61.   }, initialState);
  62.  
  63.   const pop = useCallback(() => {
  64.     alert();
  65.     dispatchState({ type: 'pop' });
  66.   }, []);
  67.  
  68.   const push = useCallback((newItem: T) => {
  69.     dispatchState({ type: 'push', payload: newItem });
  70.   }, []);
  71.  
  72.   const next = useCallback(() => {
  73.     dispatchState({ type: 'next' });
  74.   }, []);
  75.  
  76.   const current = (state.index === -1) ? null : state.list[state.index];
  77.  
  78.   return { value: current, index: state.index, list: state.list, push, pop, next };
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement