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