From 7d23632a499cadf72188f6a1f0b3be37d37725d7 Mon Sep 17 00:00:00 2001 From: AssisrMatheus Date: Thu, 8 Dec 2022 10:17:53 -0500 Subject: [PATCH] feat: adds `removeIndexArray` and `removeFromArray` --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src/helpers/array/index.ts | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 682f8c6..5256e30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +## [1.2.0] - 2022-12-08 + +### Added + +- Adds `removeIndexArray` and `removeFromArray` + ## [1.1.0] - 2022-10-24 ### Added diff --git a/package.json b/package.json index 476081e..10b44dc 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@perimetre/helpers", "description": "Our bundle with all of our utilities and reusable helpers", - "version": "1.1.0", + "version": "1.2.0", "repository": { "type": "git", "url": "git+https://github.com/perimetre/helpers.git" diff --git a/src/helpers/array/index.ts b/src/helpers/array/index.ts index 5dff05c..7d9654a 100644 --- a/src/helpers/array/index.ts +++ b/src/helpers/array/index.ts @@ -28,6 +28,19 @@ export const replaceIntoArray = , Y>(array: T, index: number, ...array.slice(index + 1) // This one skips the item, thus removing it ] as T; +/** + * Removes an item in an array at an specific index + * + * @param array the array to remove + * @param index the index to remove + * @returns a new copy of the array with the item at the given index removed + */ +export const removeIndexArray = , Y>(array: T, index: number): T => + [ + ...array.slice(0, index), + ...array.slice(index + 1) // This one skips the item, thus removing it + ] as T; + /** * Finds the next index of an array * @@ -169,3 +182,25 @@ export const shiftToPreviousIndexInArray = , Y>(array: T, ini const previousIndex = findPreviousIndex(array, (_, index) => index === initialIndex); return shiftIndexInArray(array, initialIndex, previousIndex); }; + +/** + * Removes an item from an array + * + * @param array the array to remove + * @param predicate the predicate to use to find the item to be removed + * @returns a new copy of the array with the item at the given index removed + */ +export const removeFromArray = , Y>( + array: T, + predicate: (value: T[number], index: number, arr: T[number][]) => boolean +): T => { + const index = array.findIndex(predicate); + + // If item is not found, return the original array + if (index === -1) { + // Make a copy since the user expect the original array to be untouched + return [...array] as T; + } + + return removeIndexArray(array, index); +};