sajad torkamani
export function arrayToCommaSeparatedString(
  arr: Array<string | number>,
): string {
  if (arr.length === 0) {
    return ''
  }

  if (arr.length === 1) {
    return arr[0].toString()
  }

  if (arr.length === 2) {
    return `${arr[0]} and ${arr[1]}`
  }

  return (
    arr.slice(0, arr.length - 1).join(', ') + ', and ' + arr[arr.length - 1]
  )
}

console.log(arrayToCommaSeparatedString(['foo', 'bar']))
console.log(arrayToCommaSeparatedString(['foo', 'bar', 'baz']))

replit

Leave a comment

Your email address will not be published. Required fields are marked *