4 module Puppet::Parser::Functions
5 newfunction(:clamp, :type => :rvalue, :arity => -2, :doc => <<-DOC
7 Keeps value within the range [Min, X, Max] by sort based on integer value
8 (parameter order doesn't matter).
10 Strings are converted and compared numerically. Arrays of values are flattened
11 into a list for further handling.
13 @example Example usage
15 clamp('24', [575, 187])` returns 187.
16 clamp(16, 88, 661)` returns 88.
17 clamp([4, 3, '99'])` returns 4.
20 From Puppet 6.0.0 this can be done with only core Puppet like this:
21 `[$minval, $maxval, $value_to_clamp].sort[1]`
23 @return [Array[Integer]] The sorted Array
29 raise(Puppet::ParseError, 'clamp(): Wrong number of arguments, need three to clamp') if args.size != 3
35 raise(Puppet::ParseError, "clamp(): Required explicit numeric (#{value}:String)") unless value =~ %r{^\d+$}
37 raise(Puppet::ParseError, "clamp(): The Hash type is not allowed (#{value})")
41 # convert to numeric each element
42 # then sort them and get a middle value
43 args.map { |n| n.to_i }.sort[1]