Skip to content

Commit

Permalink
Add new utils for wrapping & flattening arrays.
Browse files Browse the repository at this point in the history
  • Loading branch information
jgaehring committed Feb 13, 2023
1 parent c8468e5 commit f4565c7
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions packages/field-kit/src/utils/asArray.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit f4565c7

Please sign in to comment.