Created
June 20, 2023 23:33
-
-
Save christianvmm/6d9e5f8f19cc3ed2539a9eeb2328d378 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useState } from 'react' | |
| type FilterFunction<T> = (item: T) => boolean | |
| export function useArray<T>() { | |
| const [data, setData] = useState<Array<T>>([]) | |
| function push(value: T): void { | |
| setData((prev) => [...prev, value]) | |
| } | |
| function set(data: Array<T>): void { | |
| setData(data) | |
| } | |
| function clear(): void { | |
| setData([]) | |
| } | |
| function filter(f: FilterFunction<T>): void { | |
| setData((prev) => prev.filter(f)) | |
| } | |
| function update(index: number, newValue: T): void { | |
| setData((prev) => [ | |
| ...prev.slice(0, index), | |
| newValue, | |
| ...prev.slice(index + 1, prev.length - 1), | |
| ]) | |
| } | |
| function remove(index: number): void { | |
| setData((prev) => [ | |
| ...prev.slice(0, index), | |
| ...prev.slice(index + 1, prev.length - 1), | |
| ]) | |
| } | |
| return { | |
| data, | |
| push, | |
| set, | |
| clear, | |
| filter, | |
| update, | |
| remove, | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment