0a1a9400b16f681f346d26f7c7f2ca66db6dd61b
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / delete_at.rb
1 #
2 # delete_at.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:delete_at, :type => :rvalue, :doc => <<-DOC
6     Deletes a determined indexed value from an array.
7
8     *Examples:*
9
10         delete_at(['a','b','c'], 1)
11
12     Would return: ['a','c']
13
14     Note that since Puppet 4 this can be done in general with the filter function:
15
16         ['a', 'b', 'c'].filter |$pos, $val | { $pos != 1 }
17
18     Or if a delete is wanted from the beginning or end of the array, by using the slice operator [ ]:
19
20         $array[0, -1] # the same as all the values
21         $array[2, -1] # all but the first 2 elements
22         $array[0, -3] # all but the last 2 elements
23         $array[1, -2] # all but the first and last element
24   DOC
25              ) do |arguments|
26
27     raise(Puppet::ParseError, "delete_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2
28
29     array = arguments[0]
30
31     unless array.is_a?(Array)
32       raise(Puppet::ParseError, 'delete_at(): Requires array to work with')
33     end
34
35     index = arguments[1]
36
37     if index.is_a?(String) && !index.match(%r{^\d+$})
38       raise(Puppet::ParseError, 'delete_at(): You must provide non-negative numeric index')
39     end
40
41     result = array.clone
42
43     # Numbers in Puppet are often string-encoded which is troublesome ...
44     index = index.to_i
45
46     if index > result.size - 1 # First element is at index 0 is it not?
47       raise(Puppet::ParseError, 'delete_at(): Given index exceeds size of array given')
48     end
49
50     result.delete_at(index) # We ignore the element that got deleted ...
51
52     return result
53   end
54 end
55
56 # vim: set ts=2 sw=2 et :