forked from farmOS/field-kit
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add new utils for wrapping & flattening arrays.
- Loading branch information
Showing
1 changed file
with
14 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |