Module: Linked::ListEnumerable

Includes:
Enumerable
Included in:
List
Defined in:
lib/linked/list_enumerable.rb

Overview

Expects the list to implement #list_head and #list_tail.

Instance Method Summary collapse

Instance Method Details

#count(*args) ⇒ Integer

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.

Parameters:

  • args (Array<Object>)

    see Enumerable#count

Returns:

  • (Integer)

    the number of items counted.



75
76
77
78
79
80
81
# 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_itemObject Also known as: each

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



10
11
12
13
14
15
16
17
18
19
# 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

#first(n = nil) ⇒ Listable+

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

Parameters:

  • n (Integer) (defaults to: nil)

    the number of items to return.

Returns:

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
53
# 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) ⇒ Listable+

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

Parameters:

  • n (Integer) (defaults to: nil)

    the number of items to return.

Returns:

  • (Listable)

    if n = nil.

  • (Array<Listable>)

    if n >= 0. The order is preserved.

Raises:

  • (ArgumentError)


60
61
62
63
64
65
66
67
# 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_item {|Listable| ... } ⇒ Enumerable Also known as: reverse_each

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

Yields:

Returns:

  • (Enumerable)

    if no block is given.



28
29
30
31
32
33
34
35
36
37
# 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