From 760de608e38e92082964246ab53397acd741e31d Mon Sep 17 00:00:00 2001 From: Carlos Valente Date: Sat, 28 Dec 2024 21:26:40 +0100 Subject: [PATCH] refactor: simplify logic --- .../utils/src/array-utils/arrayUtils.test.ts | 35 ++++++++++++++++++- packages/utils/src/array-utils/arrayUtils.ts | 2 +- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/packages/utils/src/array-utils/arrayUtils.test.ts b/packages/utils/src/array-utils/arrayUtils.test.ts index e8397d06d..bc0a56474 100644 --- a/packages/utils/src/array-utils/arrayUtils.test.ts +++ b/packages/utils/src/array-utils/arrayUtils.test.ts @@ -1,4 +1,4 @@ -import { insertAtIndex, reorderArray } from './arrayUtils.js'; +import { deleteAtIndex, insertAtIndex, reorderArray } from './arrayUtils.js'; describe('insertAtIndex', () => { it('should insert an item at the beginning of the array', () => { @@ -27,6 +27,39 @@ describe('insertAtIndex', () => { }); }); +describe('deleteAtIndex', () => { + it('should delete an item at the beginning of the array', () => { + const array = [1, 2, 3, 4]; + const result = deleteAtIndex(0, array); + expect(result).toEqual([2, 3, 4]); + }); + + it('should delete an item at the end of the array', () => { + const array = [1, 2, 3, 4]; + const result = deleteAtIndex(3, array); + expect(result).toEqual([1, 2, 3]); + }); + + it('should delete an item in the middle of the array', () => { + const array = [1, 2, 3, 4]; + const result = deleteAtIndex(2, array); + expect(result).toEqual([1, 2, 4]); + }); + + it('should return a new array and not modify the original array', () => { + const array = [1, 2, 3, 4]; + const result = deleteAtIndex(1, array); + expect(result).toEqual([1, 3, 4]); + expect(array).toEqual([1, 2, 3, 4]); // Original array should remain unchanged + }); + + it('should return the original array if the index is out of bounds', () => { + const array = [1, 2, 3, 4]; + const result = deleteAtIndex(10, array); + expect(result).toEqual([1, 2, 3, 4]); + }); +}); + describe('reorderArray', () => { it('should reorder an item in the array', () => { const array = ['a', 'b', 'c', 'd']; diff --git a/packages/utils/src/array-utils/arrayUtils.ts b/packages/utils/src/array-utils/arrayUtils.ts index 3209004ca..182df39ba 100644 --- a/packages/utils/src/array-utils/arrayUtils.ts +++ b/packages/utils/src/array-utils/arrayUtils.ts @@ -31,7 +31,7 @@ export function insertAtIndex(index: number, item: T, array: T[]): T[] { * @param array */ export function deleteAtIndex(index: number, array: T[]) { - return array.filter((_, i) => i !== index); + return array.toSpliced(index, 1); } /**