Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 19 additions & 32 deletions lib/ruby_units/unit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -259,56 +259,43 @@ def self.parse(input)
second.nil? ? new(first) : new(first).convert_to(second)
end

# @param [Numeric] q quantity
# @param [Array] n numerator
# @param [Array] d denominator
# @param q [Numeric] quantity
# @param n [Array] numerator
# @param d [Array] denominator
# @return [Hash]
def self.eliminate_terms(q, n, d)
num = n.dup
den = d.dup
num.delete(UNITY)
den.delete(UNITY)

num.delete_if { |v| v == UNITY }
den.delete_if { |v| v == UNITY }
combined = Hash.new(0)

i = 0
loop do
break if i > num.size
if @@prefix_values.key? num[i]
k = [num[i], num[i + 1]]
i += 2
else
k = num[i]
i += 1
end
combined[k] += 1 unless k.nil? || k == UNITY
end

j = 0
loop do
break if j > den.size
if @@prefix_values.key? den[j]
k = [den[j], den[j + 1]]
j += 2
else
k = den[j]
j += 1
end
combined[k] -= 1 unless k.nil? || k == UNITY
[[num, 1], [den, -1]].each do |array, increment|
array.chunk_while { |elt_before, _| definition(elt_before).prefix? }
.to_a
.each { |unit| combined[unit] += increment }
end

num = []
den = []
combined.each do |key, value|
if value >= 0
if value.positive?
value.times { num << key }
elsif value < 0
elsif value.negative?
value.abs.times { den << key }
end
end
num = UNITY_ARRAY if num.empty?
den = UNITY_ARRAY if den.empty?
{ scalar: q, numerator: num.flatten.compact, denominator: den.flatten.compact }
{ scalar: q, numerator: num.flatten, denominator: den.flatten }
end

# Creates a new unit from the current one with all common terms eliminated.
#
# @return [RubyUnits::Unit]
def eliminate_terms
self.class.new(self.class.eliminate_terms(@scalar, @numerator, @denominator))
end

# return an array of base units
Expand Down
17 changes: 17 additions & 0 deletions spec/ruby_units/unit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1514,6 +1514,23 @@
it { is_expected.to be === subject }
end
end

describe '#eliminate_terms' do
subject(:unit) { RubyUnits::Unit.new('1 kg*m/kg*s').eliminate_terms }

it 'returns a new Unit' do
expect(unit).to be_a(RubyUnits::Unit)
end

it 'the new unit has common terms removed' do
expect(unit).to have_attributes(
to_s: '1 m/s',
denominator: ['<second>'],
kind: :speed,
numerator: ['<meter>']
)
end
end
end

describe 'Unit Comparisons' do
Expand Down