@trellixio/roaster-coffee
Version:
Beans' product component library
97 lines (96 loc) • 2.87 kB
JavaScript
import { useState } from 'react';
/**
* A custom React Hook that implements a queue with a fixed limit.
*
* @remarks
* This Hook provides functionality for adding items to the queue, updating the state of the queue, and cleaning the queue.
*
* @typeParam T - The type of the items in the queue.
* @param options - An options object.
* ```typescript
* {
* initialValues?: T[]; // - An array of initial values for the queue.
* limit: number; // - The maximum number of items allowed in the queue.
* }
*```
* @returns An object containing the current state of the queue, as well as functions for adding items, updating the queue, and cleaning the queue.
*
* @example
* Usage example:
*```tsx
* import { useQueue } from './useQueue';
*
* function MyComponent() {
* const { state, queue, add, update, cleanQueue } = useQueue<string>({ initialValues: [], limit: 3 });
*
* // Add some items to the queue
* add('item 1', 'item 2', 'item 3', 'item 4', 'item 5');
*
* // Update the state of the queue
* update((currentState) => {
* return currentState.filter((item) => item !== 'item 3');
* });
*
*
* return (
* <div>
* <h1>Current state:</h1>
* <ul>
* {state.map((item, index) => (
* <li key={index}>{item}</li>
* ))}
* </ul>
* <h1>Queue:</h1>
* <ul>
* {queue.map((item, index) => (
* <li key={index}>{item}</li>
* ))}
* </ul>
* <button onClick={() => cleanQueue()}>Clear queue</button>
* </div>
* );
* }
* ```
*
*/
export function useQueue({ initialValues = [], limit }) {
const [{ state, queue }, setState] = useState({
state: initialValues.slice(0, limit),
queue: initialValues.slice(limit),
});
/**
* Adds one or more items to the queue.
*
* @param items - \<T[]\> One or more items to add to the queue.
*/
const add = (...items) => setState((current) => {
const results = [...current.state, ...current.queue, ...items];
return {
state: results.slice(0, limit),
queue: results.slice(limit),
};
});
/**
* Updates the state of the queue by applying a function to the current state.
*
* @param fn - A function that takes the current state of the queue as an argument and returns a new state.
*/
const update = (fn) => setState((current) => {
const results = fn([...current.state, ...current.queue]);
return {
state: results.slice(0, limit),
queue: results.slice(limit),
};
});
/**
* Clears the queue.
*/
const cleanQueue = () => setState((current) => ({ state: current.state, queue: [] }));
return {
state,
queue,
add,
update,
cleanQueue,
};
}