-
-
Save anselm-helbig/d03c77fbc0ca55b208a5b4b479ee83d1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'test_helper' | |
module Kindlemd | |
Chapter = Struct.new(:position, :nxt, :previous) do | |
def self.normalize(chapters) | |
chapters = chapters.map { |h| new(h[:position]) }.sort_by(&:position) | |
chapters.each_cons(2) { |previous, nxt| | |
previous.nxt = nxt | |
nxt.previous = previous | |
} | |
chapters.map(&:to_h) | |
end | |
def to_h | |
h = { position: position } | |
h[:next] = nxt.position if nxt | |
h[:previous] = previous.position if previous | |
h | |
end | |
end | |
end | |
class ChapterTest < Minitest::Test | |
def chapters | |
[ | |
{ | |
position: 324 | |
}, | |
{ | |
position: 328 | |
}, | |
{ | |
position: 887 | |
}, | |
{ | |
position: 105 | |
}, | |
{ | |
position: 639 | |
} | |
] | |
end | |
def expected | |
[ | |
{ | |
position: 105, | |
next: 324, | |
}, | |
{ | |
position: 324, | |
next: 328, | |
previous: 105 | |
}, | |
{ | |
position: 328, | |
next: 639, | |
previous: 324 | |
}, | |
{ | |
position: 639, | |
next: 887, | |
previous: 328 | |
}, | |
{ | |
position: 887, | |
previous: 639 | |
} | |
] | |
end | |
def test_that_it_normalizes | |
assert_equal expected, Kindlemd::Chapter.normalize(chapters) | |
end | |
def test_that_it_works_with_empty | |
assert_equal [], Kindlemd::Chapter.normalize([]) | |
end | |
def test_that_it_works_with_one_element | |
assert_equal [{position: 1}], Kindlemd::Chapter.normalize([{position: 1}]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!
I did: