-
Notifications
You must be signed in to change notification settings - Fork 161
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
closes #157
- Loading branch information
Showing
4 changed files
with
51 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
require_relative '../function' | ||
|
||
Dentaku::AST::Function.register(:avg, :numeric, ->(*args) { | ||
if args.empty? | ||
raise Dentaku::ArgumentError.for( | ||
:too_few_arguments, | ||
function_name: 'AVG()', at_least: 1, given: 0 | ||
), 'AVG() requires at least one argument' | ||
end | ||
|
||
flatten_args = args.flatten | ||
flatten_args.map { |arg| Dentaku::AST::Function.numeric(arg) }.reduce(0, :+) / flatten_args.length | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
require 'spec_helper' | ||
require 'dentaku/ast/functions/avg' | ||
require 'dentaku' | ||
|
||
describe 'Dentaku::AST::Function::Avg' do | ||
it 'returns the average of an array of Numeric values' do | ||
result = Dentaku('AVG(1, x, 1.8)', x: 2.3) | ||
expect(result).to eq 1.7 | ||
end | ||
|
||
it 'returns the average of a single entry array of a Numeric value' do | ||
result = Dentaku('AVG(x)', x: 2.3) | ||
expect(result).to eq 2.3 | ||
end | ||
|
||
it 'returns the average even if a String is passed' do | ||
result = Dentaku('AVG(1, x, 1.8)', x: '2.3') | ||
expect(result).to eq 1.7 | ||
end | ||
|
||
it 'returns the average even if an array is passed' do | ||
result = Dentaku('AVG(1, x, 2.3)', x: [4, 5]) | ||
expect(result).to eq 3.075 | ||
end | ||
|
||
context 'checking errors' do | ||
let(:calculator) { Dentaku::Calculator.new } | ||
|
||
it 'raises an error if no arguments are passed' do | ||
expect { calculator.evaluate!('AVG()') }.to raise_error(ArgumentError) | ||
end | ||
end | ||
end |