From: Krzysztof Wilczynski Date: Fri, 29 Apr 2011 16:29:14 +0000 (+0100) Subject: Small re-factor of shuffle function. It is more compact now. X-Git-Url: https://gitweb.fluxo.info/?a=commitdiff_plain;h=b3dd2207c3eefe4a74f86188330a0117b6f03da9;p=puppet-stdlib.git Small re-factor of shuffle function. It is more compact now. Signed-off-by: Krzysztof Wilczynski --- diff --git a/shuffle.rb b/shuffle.rb index c7abf30..2bba584 100644 --- a/shuffle.rb +++ b/shuffle.rb @@ -18,27 +18,25 @@ module Puppet::Parser::Functions 'array or string to work with') end - string_given = false - result = value.clone - if value.is_a?(String) - result = result.split('') - string_given = true - end - - elements = result.size + string_type = value.is_a?(String) ? true : false - return [] if result.size == 0 + # Check whether it makes sense to shuffle ... return result if result.size <= 1 + # We turn any string value into an array to be able to shuffle ... + result = string_type ? result.split('') : result + + elements = result.size + # Simple implementation of Fisher–Yates in-place shuffle ... elements.times do |i| j = rand(elements - i) + i result[j], result[i] = result[i], result[j] end - result = string_given ? result.join : result + result = string_type ? result.join : result return result end