Skip to content

Instantly share code, notes, and snippets.

@anselm-helbig
Forked from abuiles/chapter_test.rb
Last active March 13, 2017 19:41
Show Gist options
  • Save anselm-helbig/d03c77fbc0ca55b208a5b4b479ee83d1 to your computer and use it in GitHub Desktop.
Save anselm-helbig/d03c77fbc0ca55b208a5b4b479ee83d1 to your computer and use it in GitHub Desktop.
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
@abuiles
Copy link

abuiles commented Mar 13, 2017

Nice!

I did:

def  self.normalize(chapters)
      enum = chapters.sort{ |c,d|
        c[:location] <=> d[:location]
      }.to_enum

      searching = true

      while searching
        begin
          chapter = enum.next
          next_chapter = enum.peek
          chapter[:next_chapter] = next_chapter[:location]
          next_chapter[:previous] = chapter[:location]
        rescue StopIteration
          searching = false
        end
      end

      enum.to_a
    end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment