Last active
February 28, 2019 09:47
IOTA for ruby
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
# inspired by https://github.com/golang/go/wiki/Iota | |
module IOTA | |
class Counter | |
def initialize(start, increment, max) | |
@start = start | |
@times = 0 | |
@increment = increment | |
@max = max | |
end | |
def next | |
actual = @start + (@times * @increment) | |
if !@max.nil? && actual > @max | |
raise "#{actual} exceeds max #{@max}! #{self}" | |
end | |
@times += 1 | |
actual | |
end | |
def to_s | |
"IOTA(start=#{@start},times=#{@times},increment=#{@increment},max=#{@max})" | |
end | |
end | |
def with_iota(start: 0, increment: 1, max: nil) | |
yield Counter.new(start, increment, max) | |
end | |
end | |
if __FILE__ == $0 | |
# run tests with ruby iota.rb | |
require "minitest/autorun" | |
class IOTATest < Minitest::Test | |
include IOTA | |
def test_works_with_defaults | |
with_iota do |iota| | |
assert_equal 0, iota.next | |
assert_equal 1, iota.next | |
assert_equal 2, iota.next | |
assert_equal 3, iota.next | |
assert_equal 4, iota.next | |
end | |
end | |
def test_works_with_increment | |
with_iota(start: 1, increment: 2) do |iota| | |
assert_equal 1, iota.next | |
assert_equal 3, iota.next | |
assert_equal 5, iota.next | |
end | |
end | |
def test_works_with_max | |
with_iota(start: 1, increment: 2, max: 5) do |iota| | |
assert_equal 1, iota.next | |
assert_equal 3, iota.next | |
assert_equal 5, iota.next | |
assert_raises do | |
iota.next | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment