Module: Transproc::Recursion

Extended by:
Functions
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", "zipcode" => "123" }]
# => {:name=>"Jane", :address=>{:street=>"Street 1", :zipcode=>"123"}}

Constant Summary collapse

IF_ARRAY =
-> fn { Transproc(:is, Array, fn) }
IF_HASH =
-> fn { Transproc(:is, Hash, fn) }

Instance Method Summary collapse

Methods included from Functions

method_added

Instance 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)


37
38
39
40
41
42
43
44
# File 'lib/transproc/recursion.rb', line 37

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

  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)


59
60
61
62
63
64
65
66
67
68
# File 'lib/transproc/recursion.rb', line 59

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

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

  result
end