lib/abstract_mapper/functions.rb in abstract_mapper-0.0.1 vs lib/abstract_mapper/functions.rb in abstract_mapper-0.0.2

- old
+ new

@@ -8,12 +8,26 @@ # module Functions extend Transproc::Registry - uses :map_array, from: Transproc::ArrayTransformations + import :map_array, from: Transproc::ArrayTransformations + # Returns the unchanged value whatever parameters are given + # + # @example + # fn = Functions[:identity, :foo] + # fn[1] # => 1 + # + # @param [Object] value + # + # @return [Object] + # + def self.identity(value, *) + value + end + # Applies the function to every element of array and removes empty values # # @example # fn = Functions[:filter, -> v { v - 1 if v > 3 }] # fn[[1, 4, 5, 3, 2, 5, 9]] @@ -22,12 +36,12 @@ # @param [Array] array # @param [Proc] fn # # @return [Array] # - def filter(array, fn) - map_array(array, fn).compact.flatten + def self.filter(array, fn) + t(:map_array, fn)[array].compact.flatten end # Applies the function to every consecutive pair of array elements, # and removes empty values # @@ -42,11 +56,11 @@ # Anonymous function (proc, lambda), that takes two arguments # and returns an array # # @return [Array] # - def compact(array, fn) + def self.compact(array, fn) array.each_with_object([]) do |i, a| if a.empty? a << i else a[-1] = fn.call(a.last, i) @@ -65,11 +79,24 @@ # @param [Module] subling # @param [Module] ancestor # # @return [Boolean] # - def subclass?(subling, ancestor) + def self.subclass?(subling, ancestor) subling.ancestors.include?(ancestor) + end + + # Restricts the hash by keys and values of the default one + # + # @param [Hash] hash + # @param [Hash] default_hash + # + # @return [Hash] <description> + # + def self.restrict(hash, default_hash) + keys = default_hash.keys + values = default_hash.merge(hash).values + Hash[keys.zip(values)] end end # module Functions end # class AbstractMapper