class JMESPath::Nodes::MaxFunction

Public Instance Methods

call(args) click to toggle source
# File lib/jmespath/nodes/function.rb, line 230
def call(args)
  if args.count == 1
    values = args.first
  else
    return maybe_raise Errors::InvalidArityError, 'function max() expects one argument'
  end
  if values.respond_to?(:to_ary)
    values = values.to_ary
    return nil if values.empty?
    first = values.first
    first_type = get_type(first)
    unless first_type == NUMBER_TYPE || first_type == STRING_TYPE
      msg = String.new('function max() expects numeric or string values')
      return maybe_raise Errors::InvalidTypeError, msg
    end
    values.inject([first, first_type]) do |(max, max_type), v|
      v_type = get_type(v)
      if max_type == v_type
        v > max ? [v, v_type] : [max, max_type]
      else
        msg = String.new('function max() encountered a type mismatch in sequence: ')
        msg << "#{max_type}, #{v_type}"
        return maybe_raise Errors::InvalidTypeError, msg
      end
    end.first
  else
    return maybe_raise Errors::InvalidTypeError, 'function max() expects an array'
  end
end