Skip to content

Instantly share code, notes, and snippets.

@westc
Created October 6, 2023 18:03
Show Gist options
  • Save westc/b01e5e8fbc05abfa5c8588d68b6db9b3 to your computer and use it in GitHub Desktop.
Save westc/b01e5e8fbc05abfa5c8588d68b6db9b3 to your computer and use it in GitHub Desktop.
Takes a value and turns it into an array if it isn't already.
/**
* Takes a value and turns it into an array if it isn't already.
* @param {*} value
* The value that should be turned into an array. If this is already an
* array just return it. If this is a non-iterable value or is a string
* literal the returned value will be an array containing this value.
* Otherwise if this is iterable it will be returned as a new array.
* @returns {any[]}
* If `value` is already an array it will be returned, otherwise return a
* new array representing `value`.
*/
function parseArray(value) {
if (Array.isArray(value)) return value;
// Checking if value is iterable but not a string.
// NOTE: checking against null and undefined because `document.all == null`
// is true but not when using strict equality.
if (value !== null && value !== undefined && 'string' !== typeof value && 'function' === typeof value[Symbol.iterator]) {
try {
return [...value];
}catch(e){}
}
return [value];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment