Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / shuffle.rb
1 #
2 # shuffle.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:shuffle, :type => :rvalue, :doc => <<-DOC
6   @summary
7     Randomizes the order of a string or array elements.
8
9    @return
10      randomized string or array
11   DOC
12              ) do |arguments|
13
14     raise(Puppet::ParseError, "shuffle(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
15
16     value = arguments[0]
17
18     unless value.is_a?(Array) || value.is_a?(String)
19       raise(Puppet::ParseError, 'shuffle(): Requires either array or string to work with')
20     end
21
22     result = value.clone
23
24     string = value.is_a?(String) ? true : false
25
26     # Check whether it makes sense to shuffle ...
27     return result if result.size <= 1
28
29     # We turn any string value into an array to be able to shuffle ...
30     result = string ? result.split('') : result
31
32     elements = result.size
33
34     # Simple implementation of Fisher–Yates in-place shuffle ...
35     elements.times do |i|
36       j = rand(elements - i) + i
37       result[j], result[i] = result[i], result[j]
38     end
39
40     result = string ? result.join : result
41
42     return result
43   end
44 end
45
46 # vim: set ts=2 sw=2 et :