Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / count.rb
1 #
2 # count.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-DOC
6     @summary
7       Counts the number of elements in array.
8
9     Takes an array as first argument and an optional second argument. Counts the number of elements in array that is equal to the second argument.
10     If called with only an array, it counts the number of elements that are not nil/undef/empty-string.
11
12     > *Note:*
13       equality is tested with a Ruby method and it is therefore subject to what Ruby considers
14       to be equal. For strings this means that equality is case sensitive.
15
16     In Puppet core, counting can be done in general by using a combination of the core functions
17     filter() (since Puppet 4.0.0) and length() (since Puppet 5.5.0, before that in stdlib).
18
19     Example below shows counting values that are not undef.
20
21       ```notice([42, "hello", undef].filter |$x| { $x =~ NotUndef }.length)```
22
23     Would notice the value 2.
24
25     @return [Integer] The amount of elements counted within the array
26   DOC
27              ) do |args|
28
29     if args.size > 2
30       raise(ArgumentError, "count(): Wrong number of arguments given #{args.size} for 1 or 2.")
31     end
32
33     collection, item = args
34
35     if item
36       collection.count item
37     else
38       collection.count { |obj| !obj.nil? && obj != :undef && obj != '' }
39     end
40   end
41 end