github.com/mymmsc/gox@v1.3.33/util/linkedliststack/iterator.go (about)

     1  // Copyright (c) 2015, Emir Pasic. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package linkedliststack
     6  
     7  import "github.com/mymmsc/gox/util"
     8  
     9  func assertIteratorImplementation() {
    10  	var _ util.IteratorWithIndex = (*Iterator)(nil)
    11  }
    12  
    13  // Iterator returns a stateful iterator whose values can be fetched by an index.
    14  type Iterator struct {
    15  	stack *Stack
    16  	index int
    17  }
    18  
    19  // Iterator returns a stateful iterator whose values can be fetched by an index.
    20  func (stack *Stack) Iterator() Iterator {
    21  	return Iterator{stack: stack, index: -1}
    22  }
    23  
    24  // Next moves the iterator to the next element and returns true if there was a next element in the container.
    25  // If Next() returns true, then next element's index and value can be retrieved by Index() and Value().
    26  // If Next() was called for the first time, then it will point the iterator to the first element if it exists.
    27  // Modifies the state of the iterator.
    28  func (iterator *Iterator) Next() bool {
    29  	if iterator.index < iterator.stack.Size() {
    30  		iterator.index++
    31  	}
    32  	return iterator.stack.withinRange(iterator.index)
    33  }
    34  
    35  // Value returns the current element's value.
    36  // Does not modify the state of the iterator.
    37  func (iterator *Iterator) Value() interface{} {
    38  	value, _ := iterator.stack.list.Get(iterator.index) // in reverse (LIFO)
    39  	return value
    40  }
    41  
    42  // Index returns the current element's index.
    43  // Does not modify the state of the iterator.
    44  func (iterator *Iterator) Index() int {
    45  	return iterator.index
    46  }
    47  
    48  // Begin resets the iterator to its initial state (one-before-first)
    49  // Call Next() to fetch the first element if any.
    50  func (iterator *Iterator) Begin() {
    51  	iterator.index = -1
    52  }
    53  
    54  // First moves the iterator to the first element and returns true if there was a first element in the container.
    55  // If First() returns true, then first element's index and value can be retrieved by Index() and Value().
    56  // Modifies the state of the iterator.
    57  func (iterator *Iterator) First() bool {
    58  	iterator.Begin()
    59  	return iterator.Next()
    60  }