5 module Puppet::Parser::Functions
6 newfunction(:shuffle, :type => :rvalue, :doc => <<-EOS
7 Randomizes the order of a string or array elements.
11 raise(Puppet::ParseError, "shuffle(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1
15 unless value.is_a?(Array) || value.is_a?(String)
16 raise(Puppet::ParseError, 'shuffle(): Requires either array or string to work with')
21 string = value.is_a?(String) ? true : false
23 # Check whether it makes sense to shuffle ...
24 return result if result.size <= 1
26 # We turn any string value into an array to be able to shuffle ...
27 result = string ? result.split('') : result
29 elements = result.size
31 # Simple implementation of Fisher–Yates in-place shuffle ...
33 j = rand(elements - i) + i
34 result[j], result[i] = result[i], result[j]
37 result = string ? result.join : result
43 # vim: set ts=2 sw=2 et :