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