From 9a79ac169ce1e7bff6958580e9f2eee4b2e89cfa Mon Sep 17 00:00:00 2001 From: Ankit Kumar Date: Fri, 26 Jan 2024 13:33:28 +0530 Subject: [PATCH] Add Solution for usearray_en.md --- react/usearray_en.md | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/react/usearray_en.md b/react/usearray_en.md index 23cbe4f6..ba54b6ac 100644 --- a/react/usearray_en.md +++ b/react/usearray_en.md @@ -1,4 +1,44 @@ +Requirements +- `removeAtIndex` method +- `push` method -There is no solution yet. +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. -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) +``` +// Solution by [Ankit Kumar](https://github.com/mynameisankit) + +import { useState, useCallback, Dispatch, SetStateAction } from 'react' + +type UseArrayActions = { + push: (item: T) => void, + removeByIndex: (index: number) => void +} + +function removeAtIndex(index: number, array: T[], setArray: Dispatch>): void { + const partBeforeIndex = array.slice(0, index) || []; + const partAfterIndex = array.slice(index + 1) || []; + + const updatedArray = [...partBeforeIndex, ...partAfterIndex]; + + setArray(updatedArray); +} + +function pushValue(value: T, array: T[], setArray: Dispatch>): void { + const updatedArray = [...array, value]; + + setArray(updatedArray); +} + +export function useArray(initialValue: T[]= []): { value: T[] } & UseArrayActions { + const [array, setArray] = useState([...initialValue]); + + const removeByIndex = useCallback((index: number) => removeAtIndex(index, array, setArray), []); + const push = useCallback((value: T) => pushValue(value, array, setArray), []); + + return { + value: array, + removeByIndex, + push, + }; +} +```