From 918ceebc170d265de1dd4e25ac167902b0e58bfc Mon Sep 17 00:00:00 2001 From: LB Johnston Date: Mon, 23 Oct 2023 08:21:46 +1000 Subject: [PATCH] Create a JavaScript util `castArray` - Allows easy conversion of any value/s supplied into an array or keep as an array if it's already one --- client/src/utils/castArray.test.js | 28 ++++++++++++++++++++++++++++ client/src/utils/castArray.ts | 5 +++++ 2 files changed, 33 insertions(+) create mode 100644 client/src/utils/castArray.test.js create mode 100644 client/src/utils/castArray.ts diff --git a/client/src/utils/castArray.test.js b/client/src/utils/castArray.test.js new file mode 100644 index 0000000000..7702fc9fba --- /dev/null +++ b/client/src/utils/castArray.test.js @@ -0,0 +1,28 @@ +import { castArray } from './castArray'; + +describe('castArray', () => { + it('should return an empty array by default', () => { + expect(castArray()).toEqual([]); + }); + + it('should the provided argument wrapped as an array if it is not one', () => { + expect(castArray(null)).toEqual([null]); + expect(castArray(undefined)).toEqual([undefined]); + expect(castArray(3)).toEqual([3]); + }); + + it('should return the provided argument as an array if it is one', () => { + expect(castArray([])).toEqual([]); + expect(castArray([1, 2, 3])).toEqual([1, 2, 3]); + expect(castArray([1, 2, ['nested', 'true']])).toEqual([ + 1, + 2, + ['nested', 'true'], + ]); + }); + + it('should return a set of arguments as an array', () => { + expect(castArray(1, 2, 3)).toEqual([1, 2, 3]); + expect(castArray(null, undefined)).toEqual([null, undefined]); + }); +}); diff --git a/client/src/utils/castArray.ts b/client/src/utils/castArray.ts new file mode 100644 index 0000000000..734ec5086e --- /dev/null +++ b/client/src/utils/castArray.ts @@ -0,0 +1,5 @@ +/** + * Converts the provided args or single argument to an array. + * Even if not originally supplied as one. + */ +export const castArray = (...args) => args.flat(1);