From 0314a296208f68b9211e34f7be3d5642b46be590 Mon Sep 17 00:00:00 2001 From: Andreas Schmitz Date: Wed, 25 Oct 2023 15:05:02 +0200 Subject: [PATCH] Add array util --- src/ArrayUtil/ArrayUtil.spec.ts | 17 +++++++++++++++++ src/ArrayUtil/ArrayUtil.ts | 20 ++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/ArrayUtil/ArrayUtil.spec.ts create mode 100644 src/ArrayUtil/ArrayUtil.ts diff --git a/src/ArrayUtil/ArrayUtil.spec.ts b/src/ArrayUtil/ArrayUtil.spec.ts new file mode 100644 index 000000000..a1bbd7427 --- /dev/null +++ b/src/ArrayUtil/ArrayUtil.spec.ts @@ -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([]); + }); + +}); diff --git a/src/ArrayUtil/ArrayUtil.ts b/src/ArrayUtil/ArrayUtil.ts new file mode 100644 index 000000000..695980159 --- /dev/null +++ b/src/ArrayUtil/ArrayUtil.ts @@ -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; +};