V6 How to map array results returned by calling a method inside template literals only if length > 0...?

I need to map an array results (array returned) by calling the method StoresWithStock inside template literals only when length > 0.

But I do not want to call twice the function one to check the length first and then one to map the array if the returned array is not empty… using template7 it was possible to reference the returned array inside template7 with “this”.

My code:

${((StoresWithStock(f.stores)).length > 0) ? $h`

 ${(StoresWithStock(f.stores)).map((s) => $h`

   ... //show all stores names with stock

`)}

` : $h`

... // no stores with stock!

`}

The method:

function StoresWithStock(stores) {

... // code to check which store has stock

return [stores]; //returned array with all stores with stock
}

Any ideas?

is there a way to use “this” to reference the returned array object as it was with template7?

I mean something like this:

${((StoresWithStock(f.stores)).length > 0) ? $h`

 ${(this.map((s) => $h`//not working

   ... //show all stores names with stock

`)}

` : $h`

... // no stores with stock!

`}

I think I am little lost with this part!
appreciate any ideas!

that is overuse of literals

${something.length > 0 ? something.map((item) => $h`<div>${item}</div>`) : $h`<div>Empty</div>`}
1 Like

Thank you for your reply!

Let us say “something” it is the function that returns the array filtered! stores it is the unfiltered array!

So this way I avoid calling “something” twice?
I mean

 ${something(stores).length > 0 ? 
                            
   something(stores).map((item) => $h`
      <div>${item}</div>
   `) 

: $h`
 <div>Empty</div>
`}
function something(stores) {

... // code to check which store has stock

return [stores]; //returned array with all stores with stock
}

thanks!

store the results in some variable, e.g.

var items = something(stores);

and then check this variable

Yes I think it will be good idea to do that and avoid calling the function twice!

In my case it is more complex the case than what I showed above, because it is a virtual list created by mapping an array of stores and each store has different stock according the current time to purchase from them so I need to check the stock of each store at that time while mapping each store while creating the virtual list.

I think the idea it is the best but in my case I think I need to put it inside the function I call to check the stock for each store while creating the list of stores…

var items = something(stores);

I think the idea will be good using it in my case like this:

function something(store_items) {
...
var instock_items = [items]; //according current time
return instock_items; //returned array with all items in stock according current time
}

thanks for the tips!