1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2024-07-02 18:23:28 +00:00
TiddlyWiki5/editions/tw5.com/tiddlers/filters/examples/reduce Operator (Examples).tid

62 lines
2.1 KiB
Plaintext

created: 20201004154413968
modified: 20201006181831622
tags: [[Operator Examples]] [[reduce Operator]]
title: reduce Operator (Examples)
type: text/vnd.tiddlywiki
\define add-price() [get[price]multiply{!!quantity}add<accumulator>]
\define num-items() [get[quantity]add<accumulator>]
\define join-with-commas() [<index>compare:number:gt[0]then<accumulator>addsuffix[, ]addsuffix<currentTiddler>else<currentTiddler>]
\define display-variable(name)
''<$text text=<<__name__>>/>'': <code><$text text={{{ [<__name__>getvariable[]] }}}/></code>
\end
\define reduce-tip()
Remember that <<.op reduce>> always produces output, so <<.op else>> will never trigger after <<.op reduce>>.
\end
These examples use the following predefined variables:
* <<display-variable add-price>>
* <<display-variable num-items>>
* <<display-variable join-with-commas>>
They also use the following data tiddlers:
<ul>
<$list filter="[tag[shopping]!has[draft.of]]">
<li>
''<$link><$text text=<<currentTiddler>>/></$link>'' quantity: <$text text={{!!quantity}}/>, price: <$text text={{!!price}}/>
</li>
</$list>
</ul>
Number of items:
<<.operator-example 1 "[tag[shopping]reduce<num-items>]">>
Total price:
<<.operator-example 2 "[tag[shopping]reduce<add-price>]">>
Using `<index>` to act differently on the first item than the rest:
<<.operator-example 3 "[tag[shopping]reduce<join-with-commas>]">>
Empty input, no suffix:
<<.operator-example 4 "[tag[non-existent]reduce<add-price>]">>
Note how the output contains a single item with no text. This is not "empty output" for the purposes of the <<.op else>> operator.
<$macrocall $name=".tip" _=<<reduce-tip>> />
Empty input, no suffix, followed by <<.op else>>:
<<.operator-example 5 "[tag[non-existent]reduce<add-price>else[0]]">>
Note how the output still contains a single item with no text: <<.op else>> did not trigger. If you want the value to be 0 when <<.op reduce>> has no items to process, you need to specify 0 as the initial value by passing it as a suffix to <<.op reduce>>.
Empty input, suffix provided:
<<.operator-example 6 "[tag[non-existent]reduce:0<add-price>]">>