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] \define num-items() [get[quantity]add] \define join-with-commas() [compare:number:gt[0]thenaddsuffix[, ]addsuffixelse] \define display-variable(name) ''<$text text=<<__name__>>/>'': <$text text={{{ [<__name__>getvariable[]] }}}/> \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: * <> * <> * <> They also use the following data tiddlers:
    <$list filter="[tag[shopping]!has[draft.of]]">
  • ''<$link><$text text=<>/>'' quantity: <$text text={{!!quantity}}/>, price: <$text text={{!!price}}/>
Number of items: <<.operator-example 1 "[tag[shopping]reduce]">> Total price: <<.operator-example 2 "[tag[shopping]reduce]">> Using `` to act differently on the first item than the rest: <<.operator-example 3 "[tag[shopping]reduce]">> Empty input, no suffix: <<.operator-example 4 "[tag[non-existent]reduce]">> 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" _=<> /> Empty input, no suffix, followed by <<.op else>>: <<.operator-example 5 "[tag[non-existent]reduceelse[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]">>