Convert string parameter to an array of one element
You can use Array.concat()
, since concat accepts both arrays and non arrays:
const names = (v) => [].concat(v).map(name => name.toUpperCase())
console.log(names(['Bart', 'Lisa'])) // [ 'BART', 'LISA' ]
console.log(names('Homer')) // ['HOMER']
Short solution:
[names].flat()
If names
is an array, it will be left as-is. Anything else will be converted to an array with one element.
This works because .flat()
only flattens one level by default.
If names
is not an array, [names]
makes it an array with one element, and .flat()
does nothing more because the array has no child arrays.
If names
is an array, [names]
makes it an array with one child array, and .flat()
brings the child array back up to be a parent array.
Alternative
This is more self-explanitory:
names instanceof Array ? names : [names]
This uses a simple ternary statement to do nothing to it if it is an array already or make it an array if it is not already.