How to add a comma separator after each params if param has values and dot in the end of params

Viewed 68

for example we have 3 params

function test(a,b,c){
  console.log(a + ',' + b + ',' + c +'.')
}

test('a','b','c')

will print

> a, b, c.

but in case b will be empty, the result will look with two comma, like

test('a','','c')

will print

a,,c.

we can improve like checking each var like this

function test(a,b,c){
      console.log(a + (a?',':'') + b + (b?',':'') + c +(c?'.':''))
    }

so now

 test('a','','c')

will print

a,c.

look ok, but when we have only b

test('','b','')

will print

  b,

and now we must to check values a or b exist and there is no c to print '.'

and complexity increases, but what if we have n vars, any ideas how to solve more easily

expected result is :

test('a','b','c') => a, b, c.
test('a','b','') => a, b.
test('a','','') => a.
test('','b','c') => b, c.
test('','b','') => b.
test('','','') => 
4 Answers

You can filter and use the ...rest parameter

const isParm = prm => prm !== "" && prm !== undefined && prm !== null;

const test = (...theArgs) => {
  const list = theArgs.filter(parm => isParm(parm)); 
  if (list.length > 0) console.log(`${list.join(",")}.`)
}

let x; 
test('a','b','c')
test('a',null,'c'); // null is a falsy value
test('','','c')
test('a')
test('','b')
test(x); // undefined (falsy)
test(0,0,0); // falsy values

If I understand your intention, this should do it.

function test(...args) {
  const res = args.filter(i => i).join(',')
  return res + (res && ".")
}


// Usage
console.log(test('a','','c')); // "a,c."
console.log(test('a','b','c')); // "a,b,c."
console.log(test('','','c')); // "c."
console.log(test('a', '', '')) // "a."
console.log(test('', '', '')) // ""

Using an array join approach, we can add all inputs to an array. Then filter off empty entries and join by a comma separator.

function test(a,b,c) {
    var array = [a, b, c];
    return array.filter(x => x).join(", ") + ".";
}

console.log(test('a','','c'));

Actually, a better function signature for your function would accept an array, which allows for concat with separator of any number of items.

Use Array.reduce() function to iterate each argument in argument list and add comma separator then return final string.

function test(...args){
  return args.reduce((prev, current, index) => {
    if (current.length !== 0) {
      const separator = prev.length === 0 ? "" : ",";
      prev += `${separator}${current}` 
    }
    if (index === args.length - 1) {
      prev += ".";
    }
    return prev;
  }, "");
}

console.log(test('a','','c'));

Related