HEX
Server: Apache
System: Linux dinesh8189 5.15.98-grsec-sharedvalley-2.lc.el8.x86_64 #1 SMP Thu Mar 9 09:07:30 -03 2023 x86_64
User: cgmgerenciamento1 (814285)
PHP: 8.1.26
Disabled: apache_child_terminate,dl,escapeshellarg,escapeshellcmd,exec,link,mail,openlog,passthru,pcntl_alarm,pcntl_exec,pcntl_fork,pcntl_get_last_error,pcntl_getpriority,pcntl_setpriority,pcntl_signal,pcntl_signal_dispatch,pcntl_sigprocmask,pcntl_sigtimedwait,pcntl_sigwaitinfo,pcntl_strerror,pcntl_wait,pcntl_waitpid,pcntl_wexitstatus,pcntl_wifexited,pcntl_wifsignaled,pcntl_wifstopped,pcntl_wstopsig,pcntl_wtermsig,php_check_syntax,php_strip_whitespace,popen,proc_close,proc_open,shell_exec,symlink,system
Upload Files
File: //opt/puppetlabs/puppet/lib/ruby/vendor_ruby/puppet/functions/group_by.rb
# frozen_string_literal: true

# Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block
# and the values are arrays of elements in the collection that correspond to the key.
Puppet::Functions.create_function(:group_by) do
  # @param collection A collection of things to group.
  # @example Group array of strings by length, results in e.g. `{ 1 => [a, b], 2 => [ab] }`
  #   ```puppet
  #   [a, b, ab].group_by |$s| { $s.length }
  #   ```
  # @example Group array of strings by length and index, results in e.g. `{1 => ['a'], 2 => ['b', 'ab']}`
  #   ```puppet
  #   [a, b, ab].group_by |$i, $s| { $i%2 + $s.length }
  #   ```
  # @example Group hash iterating by key-value pair, results in e.g. `{ 2 => [['a', [1, 2]]], 1 => [['b', [1]]] }`
  #   ```puppet
  #   { a => [1, 2], b => [1] }.group_by |$kv| { $kv[1].length }
  #   ```
  # @example Group hash iterating by key and value, results in e.g. `{ 2 => [['a', [1, 2]]], 1 => [['b', [1]]] }`
  #   ```puppet
  #    { a => [1, 2], b => [1] }.group_by |$k, $v| { $v.length }
  #   ```
  dispatch :group_by_1 do
    required_param 'Collection', :collection
    block_param 'Callable[1,1]', :block
    return_type 'Hash'
  end

  dispatch :group_by_2a do
    required_param 'Array', :array
    block_param 'Callable[2,2]', :block
    return_type 'Hash'
  end

  dispatch :group_by_2 do
    required_param 'Collection', :collection
    block_param 'Callable[2,2]', :block
    return_type 'Hash'
  end

  def group_by_1(collection)
    collection.group_by do |item|
      yield(item)
    end.freeze
  end

  def group_by_2a(array)
    grouped = array.size.times.zip(array).group_by do |k, v|
      yield(k, v)
    end

    grouped.each_with_object({}) do |(k, v), hsh|
      hsh[k] = v.map { |item| item[1] }
    end.freeze
  end

  def group_by_2(collection)
    collection.group_by do |k, v|
      yield(k, v)
    end.freeze
  end
end