1
# Applies a parameterized block to each element in a sequence of entries from the first
2
# argument and returns an array with the result of each invocation of the parameterized block.
4
# This function takes two mandatory arguments: the first should be an Array, Hash, or of Enumerable type
5
# (integer, Integer range, or String), and the second a parameterized block as produced by the puppet syntax:
10
# When the first argument `$a` is an Array or of enumerable type, the block is called with each entry in turn.
11
# When the first argument is a hash the entry is an array with `[key, value]`.
13
# @example Using map with two arguments
15
# # Turns hash into array of values
16
# $a.map |$x|{ $x[1] }
18
# # Turns hash into array of keys
19
# $a.map |$x| { $x[0] }
21
# When using a block with 2 parameters, the element's index (starting from 0) for an array, and the key for a hash
22
# is given to the block's first parameter, and the value is given to the block's second parameter.args.
24
# @example Using map with two arguments
26
# # Turns hash into array of values
27
# $a.map |$key,$val|{ $val }
29
# # Turns hash into array of keys
30
# $a.map |$key,$val|{ $key }
32
# @since 3.4 for Array and Hash
33
# @since 3.5 for other enumerables, and support for blocks with 2 parameters
34
# @note requires `parser = future`
36
Puppet::Functions.create_function(:map) do
37
dispatch :map_Hash_2 do
38
param 'Hash[Any, Any]', :hash
39
required_block_param 'Callable[2,2]', :block
42
dispatch :map_Hash_1 do
43
param 'Hash[Any, Any]', :hash
44
required_block_param 'Callable[1,1]', :block
47
dispatch :map_Enumerable_2 do
48
param 'Any', :enumerable
49
required_block_param 'Callable[2,2]', :block
52
dispatch :map_Enumerable_1 do
53
param 'Any', :enumerable
54
required_block_param 'Callable[1,1]', :block
57
def map_Hash_1(hash, pblock)
58
hash.map {|x, y| pblock.call(nil, [x, y]) }
61
def map_Hash_2(hash, pblock)
62
hash.map {|x, y| pblock.call(nil, x, y) }
65
def map_Enumerable_1(enumerable, pblock)
68
enum = asserted_enumerable(enumerable)
70
loop { result << pblock.call(nil, enum.next) }
76
def map_Enumerable_2(enumerable, pblock)
79
enum = asserted_enumerable(enumerable)
82
result << pblock.call(nil, index, enum.next)
90
def asserted_enumerable(obj)
91
unless enum = Puppet::Pops::Types::Enumeration.enumerator(obj)
92
raise ArgumentError, ("#{self.class.name}(): wrong argument type (#{obj.class}; must be something enumerable.")