I wrote a function which has to support two types of a paramter names
for a list of values. Internally it deals with the parameter as an array.
A single name is given as string and multiples names are given as an array of strings.
// simplified example let doSome = names => names.map(name => name.toUpperCase()) names(['Bart', 'Lisa']) // [ 'BART', 'LISA' ] names('Homer') // TypeError: names.map is not a function
I found a solution using Array.of()
in combination with flatten()
which needs some babel configuration.
doSome = names => Array.of(names).flatten().map(name => name.toUpperCase());
Is there an idiomatic way in JavaScript to get an array without a type check?
To join the array elements we use arr. join() method. This method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(,).
Create an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.
We can convert a String to a character array using either a naive for loop or the toCharArray() method. To convert a string to a string array based on a delimeter, we can use String. split() or Pattern. split() methods.
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']
You might not be able to implement it this way if you already have code depending on this function. Still, it would probably be cleaner to allow your function to accept a variable number of arguments with rest parameters.
It means you can call the function as names('Homer')
or names('Bart', 'Lisa')
:
function names(...args){ return args.map(name => name.toUpperCase()); } console.log(names('Bart', 'Lisa')); // [ 'BART', 'LISA' ] console.log(names('Homer')); // ['HOMER']
If you really want to call the function with an array as argument, you can use the spread syntax :
console.log(names(...['Bart', 'Lisa'])); // [ "BART", "LISA" ]
If you use it with a string, you'll get back an array of characters, though:
console.log(names(...'Homer')); // [ "H", "O", "M", "E", "R" ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With