Improve counter performance

I’ve got 2000 posts. The following code below, counts the number of posts, and unique number of companies and countries from my posts.

The code works, but takes 10s to build so I’m wondering if there is a better way to achieve the same result.


date = 2015-10-14T12:11:12+02:00
companies = ["Apple", "Microsoft"]
country = "Canada"
title = " Title"


{{$postCounter := 0}}
{{$.Scratch.Set "companyCounter" slice}}
{{$.Scratch.Set "countryCounter" slice}}

{{range .RegularPages}}
  {{$postCounter = add $postCounter 1}}
  {{range .Params.companies}}
    {{$.Scratch.Add "companyCounter" (slice .)}}
  {{$.Scratch.Add "countryCounter" (slice}}

{{len ($.Scratch.Get "companyCounter" | uniq)}}
{{len ($.Scratch.Get "countryCounter" | uniq)}}

Did you know that there is partialCached?

That might be what you want to use.

@davidsneighbour is right about the cache comment, but your construct looks a little too complicated. This should work:

{{$postCounter := 0}}
{{$companyCounter := 0}}
{{$countryCounter := 0}}

{{range .RegularPages}}
{{ $companyCounter = add $companyCounter (len .Params.companies) }}
{{ if }}
{{ $countryCounter = add $countryCounter 1 }}
{{ end }}
{{ end }}
1 Like

Thanks bep.

Your code works well for the postCounter and companyCounter, but the countryCounter doesn’t. It gives the same number as the postCounter.

Each markdown post has a country params and I’m looking for the number of unique countries so if a markdown post has country = “Canada” and another has the same, it counts as one.

Not sure how to do this except for the method I’ve previously shown. I did manage to get the following to work:

{{$countryCounter := slice}}
{{range .RegularPages}}
  {{$countryCounter = append $countryCounter (slice}}
{{len ($countryCounter | uniq)}}

Problem is that performance wise this is worse than the original code.

OK, I missed that …

What about:

{{ $countries := newScratch }}
{{range .RegularPages}}
{{ $countries.Set true }}
{{ end }}
{{ $countryCount := len $countries.Values }}

I’m getting the following error message:

executing "main" at <$countries.Values>: can't evaluate field Values in type *maps.Scratch