Class: Campa::List

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/campa/list.rb

Constant Summary collapse

EMPTY =
new

Instance Method Summary collapse

Constructor Details

#initialize(*elements) ⇒ List

Returns a new instance of List.



7
8
9
10
11
12
13
# File 'lib/campa/list.rb', line 7

def initialize(*elements)
  @first = nil
  @head = nil
  @tail = EMPTY

  with elements
end

Instance Method Details

#==(other) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/campa/list.rb', line 40

def ==(other)
  return false if !other.is_a?(List)

  node = first
  other_node = other.first

  loop do
    # If both node and other_node are nil
    # we managed to walk the whole list.
    # Since there was no early return (with false)
    # this means all nodes are equal.
    return node.nil? if other_node.nil?
    return false if node != other_node

    node = node.next_node
    other_node = other_node.next_node
  end
end

#each(&block) ⇒ Object



33
34
35
36
37
38
# File 'lib/campa/list.rb', line 33

def each(&block)
  return if self == EMPTY

  block.call(head)
  tail.each(&block) if tail != EMPTY
end

#headObject



21
22
23
24
25
# File 'lib/campa/list.rb', line 21

def head
  return nil if self == EMPTY

  first.value
end

#inspectObject



59
60
61
62
# File 'lib/campa/list.rb', line 59

def inspect
  @printer ||= Printer.new
  @printer.call(self)
end

#push(element) ⇒ Object



15
16
17
18
19
# File 'lib/campa/list.rb', line 15

def push(element)
  self.class.new.tap do |l|
    l.first = Node.new(value: element, next_node: first)
  end
end

#tailObject



27
28
29
30
31
# File 'lib/campa/list.rb', line 27

def tail
  return EMPTY if first.nil? || first.next_node.nil?

  self.class.new.tap { |l| l.first = @first.next_node }
end