Skip to content

Instantly share code, notes, and snippets.

@christianvmm
Created June 20, 2023 23:33
Show Gist options
  • Select an option

  • Save christianvmm/6d9e5f8f19cc3ed2539a9eeb2328d378 to your computer and use it in GitHub Desktop.

Select an option

Save christianvmm/6d9e5f8f19cc3ed2539a9eeb2328d378 to your computer and use it in GitHub Desktop.
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