source: other-projects/hathitrust/vagrant-hadoop-cluster/trunk/modules/stdlib/lib/puppet/parser/functions/shuffle.rb@ 30903

Last change on this file since 30903 was 30903, checked in by davidb, 7 years ago

Vagrant provisioning files for a 4-node Hadoop cluster. See README.txt for more details

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