diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index 4832120..ce491dc 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -626,6 +626,22 @@ module Oga return on_call_boolean(context, left) || on_call_boolean(context, right) end + ## + # Processes the `+` operator. + # + # This operator converts the left and right expressions to numbers and + # adds them together. + # + # @param [Oga::XPath::Node] ast_node + # @param [Oga::XML::NodeSet] context + # @return [Float] + # + def on_add(ast_node, context) + left, right = *ast_node + + return on_call_number(context, left) + on_call_number(context, right) + end + ## # Delegates function calls to specific handlers. # diff --git a/spec/oga/xpath/evaluator/operators/add_operator.rb b/spec/oga/xpath/evaluator/operators/add_operator.rb new file mode 100644 index 0000000..8340799 --- /dev/null +++ b/spec/oga/xpath/evaluator/operators/add_operator.rb @@ -0,0 +1,34 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'add operator' do + before do + @document = parse('12') + @evaluator = described_class.new(@document) + end + + example 'add two numbers' do + @evaluator.evaluate('1 + 2').should == 3.0 + end + + example 'add a number and a string' do + @evaluator.evaluate('1 + "2"').should == 3.0 + end + + example 'add two strings' do + @evaluator.evaluate('"1" + "2"').should == 3.0 + end + + example 'add a number and a node set' do + @evaluator.evaluate('root/a + 2').should == 3.0 + end + + example 'add two node sets' do + @evaluator.evaluate('root/a + root/b').should == 3.0 + end + + example 'return NaN when trying to add invalid values' do + @evaluator.evaluate('"" + 1').should be_nan + end + end +end