refactor: simplify logic

This commit is contained in:
Carlos Valente
2024-12-28 21:26:40 +01:00
committed by Carlos Valente
parent 0dfef732bf
commit 760de608e3
2 changed files with 35 additions and 2 deletions
@@ -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'];
+1 -1
View File
@@ -31,7 +31,7 @@ export function insertAtIndex<T>(index: number, item: T, array: T[]): T[] {
* @param array
*/
export function deleteAtIndex<T>(index: number, array: T[]) {
return array.filter((_, i) => i !== index);
return array.toSpliced(index, 1);
}
/**