There is a compact way to build a string with optional parameters like this?
let q = `CREATE "a"
${this.date ? ` SET date = '${this.date}'` : ''}
${this.description ? ` SET description = '${this.description}'` : ''}
RETURN n`;
without that else
case returning an empty string ''
?
Edit: The current results is:
CREATE "a"
RETURN n
This is just an aesthetic issue, I would prefer not having those empty lines
Using boolean operator &&
doesn't work (it returns undefined
as string):
${this.date && ` SET date = '${this.date}'`}
You can use condition && value || "", but that's almost equivalent to using ternary operator.
Another available option is to try tagged template here that discards empty values:
let date;
let description = "description";
function nonEmpty(parts) {
var res = parts[0];
for (var i=1; i<parts.length; i++) {
if (arguments[i]) // you might want to handle `0` different
res += arguments[i];
res += parts[i];
}
return res;
}
console.log(nonEmpty`Date :: ${date} and Description :: ${description}`);
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