diff --git a/packages/@ionic/utils-array/src/__tests__/index.ts b/packages/@ionic/utils-array/src/__tests__/index.ts index 4aee20fb15..2939c91cd2 100644 --- a/packages/@ionic/utils-array/src/__tests__/index.ts +++ b/packages/@ionic/utils-array/src/__tests__/index.ts @@ -1,4 +1,4 @@ -import { concurrentFilter, conform, filter, reduce, map, move } from '../'; +import { concurrentFilter, conform, filter, reduce, map, move, replace } from '../'; describe('@ionic/utils-array', () => { @@ -261,4 +261,38 @@ describe('@ionic/utils-array', () => { }); + describe('replace', () => { + + const array = ['a', 'b', 'c']; + + it('should replace first element with z', () => { + const result = replace(array, 0, 'z'); + expect(result).toEqual(['z', 'b', 'c']); + expect(result).not.toBe(array); + }); + + it('should replace last element with z', () => { + const result = replace(array, 2, 'z'); + expect(result).toEqual(['a', 'b', 'z']); + expect(result).not.toBe(array); + }); + + describe('out of bounds', () => { + + it('should leave array unchanged for index less than zero', () => { + const result = replace(array, -1, 'z'); + expect(result).toEqual(['a', 'b', 'c']); + expect(result).not.toBe(array); + }); + + it('should leave array unchanged for index greater than array index', () => { + const result = replace(array, 5, 'z'); + expect(result).toEqual(['a', 'b', 'c']); + expect(result).not.toBe(array); + }); + + }); + + }); + }); diff --git a/packages/@ionic/utils-array/src/index.ts b/packages/@ionic/utils-array/src/index.ts index 635678fede..2f3e7df475 100644 --- a/packages/@ionic/utils-array/src/index.ts +++ b/packages/@ionic/utils-array/src/index.ts @@ -87,7 +87,7 @@ export function move(array: readonly T[], fromIndex: number, toIndex: number) const element = array[fromIndex]; const result = [...array]; - if (fromIndex <= -1 || toIndex <= -1 || fromIndex >= array.length || toIndex >= array.length) { + if (fromIndex < 0 || toIndex < 0 || fromIndex >= array.length || toIndex >= array.length) { return result; } @@ -96,3 +96,17 @@ export function move(array: readonly T[], fromIndex: number, toIndex: number) return result; } + +/** + * Replace an item in an array by index. + * + * This function will return a new array with the item in the `index` position + * replaced with `item`. + */ +export function replace(array: readonly T[], index: number, item: T): T[] { + if (index < 0 || index > array.length) { + return [...array]; + } + + return [...array.slice(0, index), item, ...array.slice(index + 1)]; +}