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