4 module Puppet::Parser::Functions
5 newfunction(:shuffle, :type => :rvalue, :doc => <<-DOC
6 Randomizes the order of a string or array elements.
10 raise(Puppet::ParseError, "shuffle(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
14 unless value.is_a?(Array) || value.is_a?(String)
15 raise(Puppet::ParseError, 'shuffle(): Requires either array or string to work with')
20 string = value.is_a?(String) ? true : false
22 # Check whether it makes sense to shuffle ...
23 return result if result.size <= 1
25 # We turn any string value into an array to be able to shuffle ...
26 result = string ? result.split('') : result
28 elements = result.size
30 # Simple implementation of Fisher–Yates in-place shuffle ...
32 j = rand(elements - i) + i
33 result[j], result[i] = result[i], result[j]
36 result = string ? result.join : result
42 # vim: set ts=2 sw=2 et :