Skip to content

Commit

Permalink
fix: when removing index from array, only allow valid values
Browse files Browse the repository at this point in the history
  • Loading branch information
AssisrMatheus committed Dec 8, 2022
1 parent 7d23632 commit 45476e0
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 14 deletions.
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.1] - 2022-12-08

### Added

- Fixes when removing index from array. To only allow valid indexes to be removed

## [1.2.0] - 2022-12-08

### 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.2.0",
"version": "1.2.1",
"repository": {
"type": "git",
"url": "git+https://github.com/perimetre/helpers.git"
Expand Down
23 changes: 10 additions & 13 deletions src/helpers/array/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,18 @@ export const replaceIntoArray = <T extends Array<Y>, Y>(array: T, index: number,
* @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 =>
[
export const removeIndexArray = <T extends Array<Y>, Y>(array: T, index: number): T => {
// If item is not found, return the original array
if (index === -1 || index >= array.length) {
// Make a copy since the user expect the original array to be untouched
return [...array] as T;
}

return [
...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 @@ -193,14 +200,4 @@ export const shiftToPreviousIndexInArray = <T extends Array<Y>, Y>(array: T, ini
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);
};
): T => removeIndexArray(array, array.findIndex(predicate));

0 comments on commit 45476e0

Please sign in to comment.