-
Notifications
You must be signed in to change notification settings - Fork 0
/
useArray.ts
41 lines (33 loc) · 971 Bytes
/
useArray.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { useState } from 'react';
export const useArray = <T>(defaultValue: T[]) => {
const [array, setArray] = useState(defaultValue);
const clear = () => {
setArray([]);
};
const push = (element: T) => {
setArray((a) => [...a, element]);
};
const filter = (predicate: (item: T, index: number, arr: T[]) => boolean) => {
setArray((arr) => arr.filter(predicate));
};
const setAt = (index: number, item: T) => {
setArray((a) => [
...a.slice(0, index),
item,
...a.slice(index + 1, a.length - 1),
]);
};
const updateAt = (index: number, item: (old: T) => T) => {
setArray((a) => [
...a.slice(0, index),
item(a[index]),
...a.slice(index + 1, a.length - 1),
]);
};
const removeAt = (index: number) => {
setArray((a) => [...a.slice(0, index), ...a.slice(index + 1, a.length - 1)]);
};
return [array, setArray, {
clear, push, filter, setAt, updateAt, removeAt,
}];
};