Skip to content

Commit

Permalink
feat: adds removeIndexArray and removeFromArray
Browse files Browse the repository at this point in the history
  • Loading branch information
AssisrMatheus committed Dec 8, 2022
1 parent 64266b2 commit 7d23632
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
35 changes: 35 additions & 0 deletions src/helpers/array/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ export const replaceIntoArray = <T extends Array<Y>, 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 = <T extends Array<Y>, 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
*
Expand Down Expand Up @@ -169,3 +182,25 @@ export const shiftToPreviousIndexInArray = <T extends Array<Y>, 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 = <T extends Array<Y>, 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);
};

0 comments on commit 7d23632

Please sign in to comment.