Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / clamp.rb
1 #
2 # clamp.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:clamp, :type => :rvalue, :arity => -2, :doc => <<-DOC
6     @summary
7       Keeps value within the range [Min, X, Max] by sort based on integer value
8       (parameter order doesn't matter).
9
10     Strings are converted and compared numerically. Arrays of values are flattened
11     into a list for further handling.
12
13     @example Example usage
14
15       clamp('24', [575, 187])` returns 187.
16       clamp(16, 88, 661)` returns 88.
17       clamp([4, 3, '99'])` returns 4.
18
19     > *Note:*
20       From Puppet 6.0.0 this can be done with only core Puppet like this:
21       `[$minval, $maxval, $value_to_clamp].sort[1]`
22
23     @return [Array[Integer]] The sorted Array
24     DOC
25              ) do |args|
26
27     args.flatten!
28
29     raise(Puppet::ParseError, 'clamp(): Wrong number of arguments, need three to clamp') if args.size != 3
30
31     # check values out
32     args.each do |value|
33       case [value.class]
34       when [String]
35         raise(Puppet::ParseError, "clamp(): Required explicit numeric (#{value}:String)") unless value =~ %r{^\d+$}
36       when [Hash]
37         raise(Puppet::ParseError, "clamp(): The Hash type is not allowed (#{value})")
38       end
39     end
40
41     # convert to numeric each element
42     # then sort them and get a middle value
43     args.map { |n| n.to_i }.sort[1]
44   end
45 end