lib/linked/list.rb in linked-0.1.0 vs lib/linked/list.rb in linked-0.1.1

- old
+ new

@@ -1,5 +1,7 @@ +# frozen_string_literal: true + module Linked # List # # This module can be included in any class to give it list like behaviour. # Most importantly, the methods #head, #tail, #grow and #shrink are @@ -40,14 +42,27 @@ # @eol. It is important that this method be called during the initialization # of the including class, and that the instance variables never be accessed # directly. def initialize(*) + @eol = EOL.new list: self + @item_count = 0 + super - + end + + # When copying a list its entire item chain needs to be copied as well. + # Therefore #dup will be called on each of the original lists items, making + # this operation quite expensive. + + def initialize_dup(source) @eol = EOL.new list: self @item_count = 0 + + source.each_item { |item| push item.dup } + + super end # Access the first n item(s) in the list. # # n - the number of items to return. @@ -169,15 +184,47 @@ # Iterates over each item in the list, either in normal or reverse order. If # a block is not given an enumerator is returned. # # reverse - flips the iteration order if true. - def each(reverse: false, &block) + def each_item(reverse: false, &block) if reverse eol.before(&block) else eol.after(&block) end + end + + alias each each_item + + # Calls #freeze on all items in the list, as well as the head and the tail + # (eol). + + def freeze + eol.freeze + each_item(&:freeze) + super + end + + # Overrides the default inspect method to provide a more useful view of the + # list. + # + # Importantly this implementation supports nested lists and will return a + # tree like structure. + + def inspect(&block) + # Get the parents inspect output + res = [super] + + each_item do |item| + lines = item.inspect(&block).split "\n" + + res.push (item.last? ? '└─╴' : '├─╴') + lines.shift + padding = item.last? ? '   ' : '│  ' + lines.each { |line| res.push padding + line } + end + + res.join("\n") end # Internal method to grow the list with n elements. Never call this method # without also inserting the n elements. #