Skip to content

Commit

Permalink
feat(replace): add replace item in array by index function
Browse files Browse the repository at this point in the history
  • Loading branch information
imhoffd committed Aug 28, 2019
1 parent df34272 commit 011ddf7
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
36 changes: 35 additions & 1 deletion packages/@ionic/utils-array/src/__tests__/index.ts
Original file line number Diff line number Diff line change
@@ -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', () => {

Expand Down Expand Up @@ -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);
});

});

});

});
16 changes: 15 additions & 1 deletion packages/@ionic/utils-array/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export function move<T>(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;
}

Expand All @@ -96,3 +96,17 @@ export function move<T>(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<T>(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)];
}

0 comments on commit 011ddf7

Please sign in to comment.