From 89686b6cffa994e10ce739ef5fbd6908a1ca1944 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Fri, 29 Aug 2014 09:36:40 +0200 Subject: [PATCH] Support for the XPath mul/* operator. --- lib/oga/xpath/evaluator.rb | 16 +++++++++ .../xpath/evaluator/operators/mul_operator.rb | 34 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 spec/oga/xpath/evaluator/operators/mul_operator.rb diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index cb51f73..3c4e98d 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -674,6 +674,22 @@ module Oga return on_call_number(context, left) % on_call_number(context, right) end + ## + # Processes the `*` operator. + # + # This operator converts the left and right expressions to numbers and + # multiplies the left number with the right number. + # + # @param [Oga::XPath::Node] ast_node + # @param [Oga::XML::NodeSet] context + # @return [Float] + # + def on_mul(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/mul_operator.rb b/spec/oga/xpath/evaluator/operators/mul_operator.rb new file mode 100644 index 0000000..60f3b17 --- /dev/null +++ b/spec/oga/xpath/evaluator/operators/mul_operator.rb @@ -0,0 +1,34 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'multiplication operator' do + before do + @document = parse('23') + @evaluator = described_class.new(@document) + end + + example 'multiply two numbers' do + @evaluator.evaluate('2 * 3').should == 6.0 + end + + example 'multiply a number and a string' do + @evaluator.evaluate('2 * "3"').should == 6.0 + end + + example 'multiply two strings' do + @evaluator.evaluate('"2" * "3"').should == 6.0 + end + + example 'multiply a node set and a number' do + @evaluator.evaluate('root/a * 3').should == 6.0 + end + + example 'multiply two node sets' do + @evaluator.evaluate('root/a * root/b').should == 6.0 + end + + example 'return NaN when trying to multiply invalid values' do + @evaluator.evaluate('"" * 1').should be_nan + end + end +end