Skip to content

Instantly share code, notes, and snippets.

@phoet
Last active February 28, 2019 09:47
Show Gist options
  • Save phoet/ea85c6cb351467b9b934ba35d8be30a7 to your computer and use it in GitHub Desktop.
Save phoet/ea85c6cb351467b9b934ba35d8be30a7 to your computer and use it in GitHub Desktop.
IOTA for ruby
# 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