class Dentaku::AST::Reduce

Public Class Methods

max_param_count() click to toggle source
# File lib/dentaku/ast/functions/reduce.rb, line 11
def self.max_param_count
  5
end
min_param_count() click to toggle source
# File lib/dentaku/ast/functions/reduce.rb, line 7
def self.min_param_count
  4
end
new(*args) click to toggle source
Calls superclass method Dentaku::AST::Function::new
# File lib/dentaku/ast/functions/reduce.rb, line 15
def initialize(*args)
  super

  validate_identifier(@args[1], 'second')
  validate_identifier(@args[2], 'third')
end

Public Instance Methods

dependencies(context = {}) click to toggle source
# File lib/dentaku/ast/functions/reduce.rb, line 22
def dependencies(context = {})
  collection      = @args[0]
  memo_identifier = @args[1].identifier
  item_identifier = @args[2].identifier
  expression      = @args[3]

  collection_deps = collection.dependencies(context)
  expression_deps = expression.dependencies(context).reject do |i|
    i == memo_identifier || i.start_with?("#{memo_identifier}.") ||
    i == item_identifier || i.start_with?("#{item_identifier}.")
  end
  inital_value_deps = @args[4] ? @args[4].dependencies(context) : []

  collection_deps + expression_deps + inital_value_deps
end
validate_identifier(arg, position, message = " click to toggle source
# File lib/dentaku/ast/functions/reduce.rb, line 54
def validate_identifier(arg, position, message = "#{name}() requires #{position} argument to be an identifier")
  raise ParseError.for(:node_invalid), message unless arg.is_a?(Identifier)
end
value(context = {}) click to toggle source
# File lib/dentaku/ast/functions/reduce.rb, line 38
def value(context = {})
  collection      = Array(@args[0].value(context))
  memo_identifier = @args[1].identifier
  item_identifier = @args[2].identifier
  expression      = @args[3]
  initial_value   = @args[4] && @args[4].value(context)

  collection.reduce(initial_value) do |memo, item|
    expression.value(
      context.merge(
        FlatHash.from_hash_with_intermediates(memo_identifier => memo, item_identifier => item)
      )
    )
  end
end