module Linked::ListEnumerable

Expects the list to implement `#list_head` and `#list_tail`.

Public Instance Methods

count(*args) click to toggle source

Overrides the Enumerable#count method when given no argument to provide a fast item count. Instead of iterating over each item, the internal item count is returned.

@param args [Array<Object>] see Enumerable#count @return [Integer] the number of items counted.

Calls superclass method
# File lib/linked/list_enumerable.rb, line 75
def count(*args)
  if args.empty? && !block_given?
    empty? ? 0 : list_head.chain_length
  else
    super
  end
end
each()
Alias for: each_item
each_item() { |item| ... } click to toggle source

Iterates over each item in the list If a block is not given an enumerator is returned.

# File lib/linked/list_enumerable.rb, line 10
def each_item
  return to_enum(__method__) { count } unless block_given?
  return if empty?

  item = list_head
  loop do
    yield item
    item = item.next
  end
end
Also aliased as: each
first(n = nil) click to toggle source

Access the first n item(s) in the list.

@param n [Integer] the number of items to return. @return [Listable] if n = nil. @return [Array<Listable>] if n >= 0.

# File lib/linked/list_enumerable.rb, line 46
def first(n = nil)
  return list_head unless n
  raise ArgumentError, 'n cannot be negative' if n.negative?

  return [] if n.zero? || empty?

  list_head.take n
end
last(n = nil) click to toggle source

Access the first n item(s) in the list.

@param n [Integer] the number of items to return. @return [Listable] if n = nil. @return [Array<Listable>] if n >= 0. The order is preserved.

# File lib/linked/list_enumerable.rb, line 60
def last(n = nil)
  return empty? ? nil : list_tail unless n
  raise ArgumentError, 'n cannot be negative' if n.negative?

  return [] if n.zero? || empty?

  list_tail.take(-n)
end
reverse_each()
Alias for: reverse_each_item
reverse_each_item() { |item| ... } click to toggle source

Iterates over each item in the list in reverse order. If a block is not given an enumerator is returned.

@yield [Listable] each item in the list. @return [Enumerable] if no block is given.

# File lib/linked/list_enumerable.rb, line 28
def reverse_each_item
  return to_enum(__method__) { count } unless block_given?
  return if empty?

  item = list_tail
  loop do
    yield item
    item = item.prev
  end
end
Also aliased as: reverse_each