Class: Hamster::Splitter

Inherits:
Object
  • Object
show all
Defined in:
lib/hamster/list.rb

Overview

This class can divide a list up into 2 `List`s, one for the prefix of elements for which the block returns true, and another for all the elements after that. It guarantees that the block will only be called ONCE for each item

Defined Under Namespace

Classes: Left, Right

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(list, block) ⇒ Splitter

Returns a new instance of Splitter.


1486
1487
1488
# File 'lib/hamster/list.rb', line 1486

def initialize(list, block)
  @list, @block, @left, @right = list, block, [], EmptyList
end

Instance Attribute Details

#leftObject (readonly)

Returns the value of attribute left


1485
1486
1487
# File 'lib/hamster/list.rb', line 1485

def left
  @left
end

#rightObject (readonly)

Returns the value of attribute right


1485
1486
1487
# File 'lib/hamster/list.rb', line 1485

def right
  @right
end

Instance Method Details

#done?Boolean

Returns:

  • (Boolean)

1503
1504
1505
# File 'lib/hamster/list.rb', line 1503

def done?
  @list.empty?
end

#next_itemObject


1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
# File 'lib/hamster/list.rb', line 1490

def next_item
  unless @list.empty?
    item = @list.head
    if @block.call(item)
      @left << item
      @list = @list.tail
    else
      @right = @list
      @list  = EmptyList
    end
  end
end