From f4565c7b822e00b19bb79b9f636b111a278748d8 Mon Sep 17 00:00:00 2001 From: Jamie Gaehring Date: Tue, 24 Jan 2023 13:28:06 -0500 Subject: [PATCH] Add new utils for wrapping & flattening arrays. --- packages/field-kit/src/utils/asArray.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/field-kit/src/utils/asArray.js b/packages/field-kit/src/utils/asArray.js index fa291f09..4402a22c 100644 --- a/packages/field-kit/src/utils/asArray.js +++ b/packages/field-kit/src/utils/asArray.js @@ -1,4 +1,18 @@ // Wrap a value in an array, unless it's nullish, then return an empty array. const asArray = value => (value ? [value] : []); +// Like above, but checks if the value is already an array and if so returns it as is. +export const asFlatArray = value => (Array.isArray(value) ? value : asArray(value)); + +// Like asFlatArray() or Array.from(), but with a few more differences: unlike +// asFlatArray(), it will always return a shallow copy and will handle iterable +// objects as well; and unlike Array.from(), it will return the empty array for +// nullish values instead of throwing an exception, while all other non-nullish, +// non-iterable values will be returned wrapped in a new array. +export const fromFlatArray = value => ( + typeof value[Symbol.iterator] === 'function' + ? Array.from(value) + : (value ? [value] : []) +).flat(Infinity); + export default asArray;