Update stdlib and concat to 6.1.0 both
[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) do |arguments|
6     @summary
7       Deletes a determined indexed value from an array.
8
9     For example
10         ```delete_at(['a','b','c'], 1)```
11
12     Would return: `['a','c']`
13
14     > *Note:*
15       Since Puppet 4 this can be done in general with the built-in
16       [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
17
18       ```['a', 'b', 'c'].filter |$pos, $val | { $pos != 1 }```
19
20     Or if a delete is wanted from the beginning or end of the array, by using the slice operator [ ]:
21       ```
22       $array[0, -1] # the same as all the values
23       $array[2, -1] # all but the first 2 elements
24       $array[0, -3] # all but the last 2 elements
25       $array[1, -2] # all but the first and last element
26       ```
27
28     @return [Array] The given array, now missing the target value
29
30   DOC
31
32     raise(Puppet::ParseError, "delete_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2
33
34     array = arguments[0]
35
36     unless array.is_a?(Array)
37       raise(Puppet::ParseError, 'delete_at(): Requires array to work with')
38     end
39
40     index = arguments[1]
41
42     if index.is_a?(String) && !index.match(%r{^\d+$})
43       raise(Puppet::ParseError, 'delete_at(): You must provide non-negative numeric index')
44     end
45
46     result = array.clone
47
48     # Numbers in Puppet are often string-encoded which is troublesome ...
49     index = index.to_i
50
51     if index > result.size - 1 # First element is at index 0 is it not?
52       raise(Puppet::ParseError, 'delete_at(): Given index exceeds size of array given')
53     end
54
55     result.delete_at(index) # We ignore the element that got deleted ...
56
57     return result
58   end
59 end
60
61 # vim: set ts=2 sw=2 et :