I am writing es templates. I want to make the codes as simple as possible and at best avoid using (function(){return XXX})()
The context: When a list has nothing, prints nothing, otherwise prints the list with ul tags around.
${
// same filter 2 times
arr.filter( d=>d.prop1=="a" ).length==0
? ""
: `<ul> ${ arr.filter( d=>d.prop1=="a" ).map(d=>`<li>${d.text}</li>`) } </ul>`
}
or
${
// function makes it bulky
(function(){
let arr2 = arr.filter( d=>d.prop1=="a" );
if( arr2.length == 0 ){
return ""
}else{
return `<ul> ${ arr2.map(d=>`<li>${d.text}</li>`) } </ul>`
}
})()
}
one more context, sometimes the problem is like this:
const NAMES = [
{ name:"John" },
{ name:"Michael", nickname:"Mike" },
];
NAMES.map( n=>`name: ${n.name} ${ n.nickname? "("+n.nickname+")":"" }` ).join("\n")
// can simplify n.nickname? "("+n.nickname+")":"" ?
Anyone come up with a way to simplify these? Thanks.