Sha256: 3f5fd06855f84b49be824a1b972be0ca186510996cc8cc02b60a62a678510972

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

module Transproc

  # Conditional transformation functions
  #
  # @example
  #   require 'transproc/conditional'
  #
  #   include Transproc::Helper
  #
  #   fn = t(:guard, -> s { s.is_a?(::String) }, -> s { s.to_sym })
  #
  #   [fn[2], fn['Jane']]
  #   # => [2, :Jane]
  #
  # @api public
  module Conditional
    extend Functions

    # Apply the transformation function to subject if the predicate returns true, or return un-modified
    #
    # @example
    #   [2, 'Jane'].map do |subject|
    #     Transproc(:guard, -> s { s.is_a?(::String) }, -> s { s.to_sym })[subject]
    #   end
    #   # => [2, :Jane]
    #
    # @param [Mixed]
    #
    # @return [Mixed]
    #
    # @api public
    def guard(value, predicate, fn)
      predicate[value] ? fn[value] : value
    end

    # Calls a function when type-check passes
    #
    # @example
    #   fn = Transproc(:is, Array, -> arr { arr.map(&:upcase) })
    #   fn.call(['a', 'b', 'c']) # => ['A', 'B', 'C']
    #
    #   fn = Transproc(:is, Array, -> arr { arr.map(&:upcase) })
    #   fn.call('foo') # => "foo"
    #
    # @param [Object]
    # @param [Class]
    # @param [Proc]
    #
    # @return [Object]
    #
    # @api public
    def is(value, type, fn)
      guard(value, -> v { v.is_a?(type) }, fn)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
transproc-0.2.0 lib/transproc/conditional.rb