Skip to content
This repository was archived by the owner on Sep 1, 2024. It is now read-only.

Commit 9a79ac1

Browse files
committed
Add Solution for usearray_en.md
1 parent 176f704 commit 9a79ac1

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

react/usearray_en.md

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,44 @@
1+
Requirements
2+
- `removeAtIndex` method
3+
- `push` method
14

2-
There is no solution yet.
5+
Now, the implementation of the above methods are standard problems with the notable exception that we must update the array immutably each time. This necessity arises due to the requirement of re-rendering the component wherever this hook is utilized. React employs a strict equality check for optimization purposes, as explained in this [article](https://react.dev/learn/updating-objects-in-state), to differentiate state changes.
36

4-
Would you like to [contribute to the solution](https://github.com/BFEdev/BFE.dev-solutions/blob/main/react/usearray_en.md)? [Contribute guideline](https://github.com/BFEdev/BFE.dev-solutions#how-to-contribute)
7+
```
8+
// Solution by [Ankit Kumar](https://github.com/mynameisankit)
9+
10+
import { useState, useCallback, Dispatch, SetStateAction } from 'react'
11+
12+
type UseArrayActions<T> = {
13+
push: (item: T) => void,
14+
removeByIndex: (index: number) => void
15+
}
16+
17+
function removeAtIndex<T>(index: number, array: T[], setArray: Dispatch<SetStateAction<T[]>>): void {
18+
const partBeforeIndex = array.slice(0, index) || [];
19+
const partAfterIndex = array.slice(index + 1) || [];
20+
21+
const updatedArray = [...partBeforeIndex, ...partAfterIndex];
22+
23+
setArray(updatedArray);
24+
}
25+
26+
function pushValue<T>(value: T, array: T[], setArray: Dispatch<SetStateAction<T[]>>): void {
27+
const updatedArray = [...array, value];
28+
29+
setArray(updatedArray);
30+
}
31+
32+
export function useArray<T>(initialValue: T[]= []): { value: T[] } & UseArrayActions<T> {
33+
const [array, setArray] = useState([...initialValue]);
34+
35+
const removeByIndex = useCallback((index: number) => removeAtIndex(index, array, setArray), []);
36+
const push = useCallback((value: T) => pushValue(value, array, setArray), []);
37+
38+
return {
39+
value: array,
40+
removeByIndex,
41+
push,
42+
};
43+
}
44+
```

0 commit comments

Comments
 (0)