Updated docs re loop testing

I’ve just updated these aTbRef articles:

Also see a demo of testing for first/list loop item which I posted here.

1 Like

For those interested, here are two constrating examples to achieve the “last” function.

Method One:

Create a counter using a number, e.g. vNum. The .each() loop will cycle through until the count condition is met.

$MyNumber=vList.count;
$MyNumber=vList.count;
var vNum=0;
$MyList2.each(y){
   $CrossRef+='<a href="#'+$ID(y)^+'">'+$Name(y)+'</a>';
   if(vNum<$MyNumber){$CrossRef+=", "};
   vNum+=1;
};

Method Two:
In contrast to Method One that uses a number count, you have the loop spot when it reaches the last item in the list. (see the .last condition).

$MyList2.each(y){
   $CrossRef+='<a href="#'+$ID(y)^+'">'+$Name(y)+'</a>';
   if(y!=$MyList2.last){$CrossRef+=", "};
};

What does all the above do? It is part of a terms indexing script. Specifically, this count ensures that a common is not inserted at the end of a line, but is between items, as shown below:
image

@mwra, I think it would be good to add “real” use case example, i.e., this one, to the atbRef, this will make the instructions more actionable.

Using .first and .last the counter method is overkill and, for the beginner, not the best choice as it is more effort (more to get wrong) for the same end. Indeed, had I remembered the List.last approach yesterday when we spoke, we wouldn’t have used the more verbose counter method.

But, a case where a loop counter would be needed is if you wanted to act on only alternate list items (i.e. odd vs. even) or where the loop count was divisible by 4 or 5, etc. An example of the first is where, building one of your export tables, you wanted to add a light background fill to alternate rows (like old-fashioned computer paper) so as to make it easier to scan -read large tables for their rows. For even rows you would add a class="value" attribute to the <tr>, e.g. <tr class="fill">, or use a different class for odd vs. even rows.

As to more examples, I’m concerned not to overwhelm aTbRef’s ongoing maintenance load with larger examples that need constant review for old code or for where better techniques are available. I ready provide examples for .each() which links to further examples here, here, here and here.

Given that aTbref is a reference and not a how-to, I’m slightly reluctant to add samples better belonging to a how-to resource. At some point the resource has to have a boundary. If it gets too big to be consistently accurately maintained, it will lose its value to community. Thus, without trying to be Grinch-like, my reticence.

I’m also conscious that for the beginner, multiple choices to do the same thing can confuse (forcing a choice of the reader who is as yet insufficiently informed to mske a confident choice). It’s much easy to say “Just pick one” when one understands why different looking code actually does the same thing.

1 Like