Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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('','','') => 

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading