Skip to content

Commit

Permalink
Implemented Node#stretch
Browse files Browse the repository at this point in the history
  • Loading branch information
wedesoft committed Aug 21, 2011
1 parent ba8b274 commit fa62165
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/multiarray/operations.rb
Expand Up @@ -498,6 +498,29 @@ def clip( range = 0 .. 0xFF )
collect { |x| x.major( range.begin ).minor range.end }
end

# Stretch values from one range to another
#
# @param [Range] from Target range of values.
# @param [Range] to Source range of values.
#
# @return [Node] Array with stretched values.
def stretch(from = 0 .. 0xFF, to = 0 .. 0xFF)
if from.exclude_end?
raise "Stretching does not support ranges with end value " +
"excluded (such as #{from})"
end
if to.exclude_end?
raise "Stretching does not support ranges with end value " +
"excluded (such as #{to})"
end
if from.last != from.first
factor = (to.last - to.first).to_f / (from.last - from.first)
collect { |x| ((x - from.first) * factor).major(to.first).minor to.last }
else
(self <= from.first).conditional to.first, to.last
end
end

# Fill array with a value
#
# @param [Object] value Value to fill array with.
Expand Down
7 changes: 7 additions & 0 deletions test/tc_sequence.rb
Expand Up @@ -363,6 +363,13 @@ def test_clip
assert_equal [ C( 3, 4, 5 ) ], S[ C( 2, 4, 6 ) ].clip( 3 .. 5 ).to_a
end

def test_stretch
assert_equal [0.0, 127.5, 255.0], S[1, 2, 3].stretch(1 .. 3).to_a
assert_equal [0, 0, 255], S[1, 2, 3].stretch(2 .. 2).to_a
assert_equal [0.0, 0.5, 1.0], S[1, 2, 3].stretch(1 .. 3, 0 .. 1).to_a
assert_equal [0, 0, 1], S[1, 2, 3].stretch(2 .. 2, 0 .. 1).to_a
end

def test_sum
[ S(O), S(I) ].each do |t|
assert_equal 9, t[ 4, 2, 3 ].sum
Expand Down

0 comments on commit fa62165

Please sign in to comment.