Skip to content

Commit

Permalink
Merge pull request #30 from bdunne/numeric_clamp
Browse files Browse the repository at this point in the history
Extract Numeric#apply_min_max to #clamp
  • Loading branch information
Fryguy authored Dec 16, 2016
2 parents 7814c41 + 109358d commit 5f4349d
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ MoreCoreExtensions are a set of core extensions beyond those provided by ActiveS

#### Numeric

* core_ext/numeric/clamp.rb
* `#clamp` - Clamp a number to a minimum and/or maximum value
* core_ext/numeric/math.rb
* `#square` - Returns the square of a Numeric
* core_ext/numeric/rounding.rb
Expand Down
1 change: 1 addition & 0 deletions lib/more_core_extensions/core_ext/numeric.rb
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
require 'more_core_extensions/core_ext/numeric/clamp'
require 'more_core_extensions/core_ext/numeric/math'
require 'more_core_extensions/core_ext/numeric/rounding'
18 changes: 18 additions & 0 deletions lib/more_core_extensions/core_ext/numeric/clamp.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module MoreCoreExtensions
module NumericClamp
#
# Clamp a number to a minimum and/or maximum value.
#
# 8.clamp(nil, nil) #=> 8
# 8.clamp(9, nil) #=> 9
# 8.clamp(nil, 6) #=> 6
def clamp(min, max)
value = self
value = [value, min].max if min
value = [value, max].min if max
value
end
end
end

Numeric.send(:prepend, MoreCoreExtensions::NumericClamp)
17 changes: 17 additions & 0 deletions spec/core_ext/numeric/clamp_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
describe Numeric do
it "#clamp" do
expect(8.clamp(nil, nil)).to eq(8)
expect(8.clamp(3, nil)).to eq(8)
expect(8.clamp(13, nil)).to eq(13)
expect(8.clamp(nil, 6)).to eq(6)
expect(8.clamp(13, 16)).to eq(13)
expect(20.clamp(13, 16)).to eq(16)

expect(8.0.clamp(nil, nil)).to eq(8.0)
expect(8.0.clamp(3.0, nil)).to eq(8.0)
expect(8.0.clamp(13.0, nil)).to eq(13.0)
expect(8.0.clamp(nil, 6.0)).to eq(6.0)
expect(8.0.clamp(13.0, 16.0)).to eq(13.0)
expect(20.0.clamp(13.0, 16.0)).to eq(16.0)
end
end

0 comments on commit 5f4349d

Please sign in to comment.