Skip to content

Commit

Permalink
Merge pull request #1064 from terrestris/add-array-util
Browse files Browse the repository at this point in the history
Add array util
  • Loading branch information
hwbllmnn authored Oct 26, 2023
2 parents 8b32810 + 0314a29 commit af08b39
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/ArrayUtil/ArrayUtil.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { joinArrayWith } from './ArrayUtil';

describe('ArrayUtil', () => {

it('is defined', () => {
expect(joinArrayWith).not.toBe(undefined);
});

it('works as expected', () => {
expect(joinArrayWith([1, 2, 3], 'a')).toStrictEqual([1, 'a', 2, 'a', 3]);
});

it('works with an empty array', () => {
expect(joinArrayWith([], 'a')).toStrictEqual([]);
});

});
20 changes: 20 additions & 0 deletions src/ArrayUtil/ArrayUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Works like the standard .join, except it returns a new array with the value inserted between all values of the array
* instead of a string.
*
* @param list any array
* @param value any value
* @returns the new array
*/
export const joinArrayWith = (list: any[], value: any) => {
const newList: any[] = [];
list.forEach((item, idx) => {
if (idx === 0) {
newList.push(item);
} else {
newList.push(value);
newList.push(item);
}
});
return newList;
};

0 comments on commit af08b39

Please sign in to comment.