1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
# frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:reverse_each,
:type => :rvalue,
:arity => -1,
:doc => <<~DOC
Reverses the order of the elements of something that is iterable and optionally runs a
[lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) for each
element.
This function takes one to two arguments:
1. An `Iterable` that the function will iterate over.
2. An optional lambda, which the function calls for each element in the first argument. It must
request one parameter.
**Example:** Using the `reverse_each` function
```puppet
$data.reverse_each |$parameter| { <PUPPET CODE BLOCK> }
```
or
```puppet
$reverse_data = $data.reverse_each
```
or
```puppet
reverse_each($data) |$parameter| { <PUPPET CODE BLOCK> }
```
or
```puppet
$reverse_data = reverse_each($data)
```
When no second argument is present, Puppet returns an `Iterable` that represents the reverse
order of its first argument. This allows methods on `Iterable` to be chained.
When a lambda is given as the second argument, Puppet iterates the first argument in reverse
order and passes each value in turn to the lambda, then returns `undef`.
**Example:** Using the `reverse_each` function with an array and a one-parameter lambda
``` puppet
# Puppet will log a notice for each of the three items
# in $data in reverse order.
$data = [1,2,3]
$data.reverse_each |$item| { notice($item) }
```
When no second argument is present, Puppet returns a new `Iterable` which allows it to
be directly chained into another function that takes an `Iterable` as an argument.
**Example:** Using the `reverse_each` function chained with a `map` function.
```puppet
# For the array $data, return an array containing each
# value multiplied by 10 in reverse order
$data = [1,2,3]
$transformed_data = $data.reverse_each.map |$item| { $item * 10 }
# $transformed_data is set to [30,20,10]
```
**Example:** Using `reverse_each` function chained with a `map` in alternative syntax
```puppet
# For the array $data, return an array containing each
# value multiplied by 10 in reverse order
$data = [1,2,3]
$transformed_data = map(reverse_each($data)) |$item| { $item * 10 }
# $transformed_data is set to [30,20,10]
```
* Since 4.4.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('reverse_each')
end
|