Module: Transproc::Recursion

Extended by:
Registry
Defined in:
lib/transproc/recursion.rb

Overview

Recursive transformation functions

Examples:

require 'transproc/recursion'

include Transproc::Helper

fn = t(:hash_recursion, t(:symbolize_keys))

fn["name" => "Jane", "address" => { "street" => "Street 1" }]
# => {:name=>"Jane", :address=>{:street=>"Street 1"}}

Constant Summary collapse

IF_ENUMERABLE =
-> fn { Conditional[:is, Enumerable, fn] }
IF_ARRAY =
-> fn { Conditional[:is, Array, fn] }
IF_HASH =
-> fn { Conditional[:is, Hash, fn] }

Class Method Summary collapse

Methods included from Registry

[], contain?, fetch, import, register, store

Class Method Details

.array_recursion(value, fn) ⇒ Array

Recursively apply the provided transformation function to an array

Examples:

Transproc(:array_recursion, -> s { s.compact })[
  [['Joe', 'Jane', nil], ['Smith', 'Doe', nil]]
]
# =>  [["Joe", "Jane"], ["Smith", "Doe"]]

Parameters:

  • (Array)

Returns:

  • (Array)


86
87
88
89
90
91
92
93
# File 'lib/transproc/recursion.rb', line 86

def self.array_recursion(value, fn)
  result = fn[value]
  guarded = IF_ARRAY[-> v { array_recursion(v, fn) }]

  result.map! do |item|
    guarded[item]
  end
end

.hash_recursion(value, fn) ⇒ Hash

Recursively apply the provided transformation function to a hash

Examples:

Transproc(:hash_recursion, Transproc(:symbolize_keys))[
  ["name" => "Jane", "address" => { "street" => "Street 1", "zipcode" => "123" }]
]
# =>  {:name=>"Jane", :address=>{:street=>"Street 1", :zipcode=>"123"}}

Parameters:

  • (Hash)

Returns:

  • (Hash)


108
109
110
111
112
113
114
115
116
117
# File 'lib/transproc/recursion.rb', line 108

def self.hash_recursion(value, fn)
  result = fn[value]
  guarded = IF_HASH[-> v { hash_recursion(v, fn) }]

  result.keys.each do |key|
    result[key] = guarded[result.delete(key)]
  end

  result
end

.recursion(value, fn) ⇒ Enumerable

Recursively apply the provided transformation function to an enumerable

Examples:

Transproc(:recursion, Transproc(:is, ::Hash, Transproc(:symbolize_keys)))[
  {
    'id' => 1,
    'name' => 'Jane',
    'tasks' => [
      { 'id' => 1, 'description' => 'Write some code' },
      { 'id' => 2, 'description' => 'Write some more code' }
    ]
  }
]
=> {
     :id=>1,
     :name=>"Jane",
     :tasks=>[
       {:id=>1, :description=>"Write some code"},
       {:id=>2, :description=>"Write some more code"}
     ]
   }

Parameters:

  • (Enumerable)

Returns:

  • (Enumerable)


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/transproc/recursion.rb', line 55

def self.recursion(value, fn)
  result = fn[value]
  guarded = IF_ENUMERABLE[-> v { recursion(v, fn) }]

  case result
  when ::Hash
    result.keys.each do |key|
      result[key] = guarded[result.delete(key)]
    end
  when ::Array
    result.map! do |item|
      guarded[item]
    end
  end

  result
end