gitee.com/quant1x/gox@v1.21.2/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 (
     8  	"gitee.com/quant1x/gox/util/internal"
     9  )
    10  
    11  func assertIteratorImplementation() {
    12  	var _ internal.IteratorWithIndex = (*Iterator)(nil)
    13  }
    14  
    15  // Iterator returns a stateful iterator whose values can be fetched by an index.
    16  type Iterator struct {
    17  	stack *Stack
    18  	index int
    19  }
    20  
    21  // Iterator returns a stateful iterator whose values can be fetched by an index.
    22  func (stack *Stack) Iterator() Iterator {
    23  	return Iterator{stack: stack, index: -1}
    24  }
    25  
    26  // Next moves the iterator to the next element and returns true if there was a next element in the container.
    27  // If Next() returns true, then next element's index and value can be retrieved by Index() and Value().
    28  // If Next() was called for the first time, then it will point the iterator to the first element if it exists.
    29  // Modifies the state of the iterator.
    30  func (iterator *Iterator) Next() bool {
    31  	if iterator.index < iterator.stack.Size() {
    32  		iterator.index++
    33  	}
    34  	return iterator.stack.withinRange(iterator.index)
    35  }
    36  
    37  // Value returns the current element's value.
    38  // Does not modify the state of the iterator.
    39  func (iterator *Iterator) Value() interface{} {
    40  	value, _ := iterator.stack.list.Get(iterator.index) // in reverse (LIFO)
    41  	return value
    42  }
    43  
    44  // Index returns the current element's index.
    45  // Does not modify the state of the iterator.
    46  func (iterator *Iterator) Index() int {
    47  	return iterator.index
    48  }
    49  
    50  // Begin resets the iterator to its initial state (one-before-first)
    51  // Call Next() to fetch the first element if any.
    52  func (iterator *Iterator) Begin() {
    53  	iterator.index = -1
    54  }
    55  
    56  // First moves the iterator to the first element and returns true if there was a first element in the container.
    57  // If First() returns true, then first element's index and value can be retrieved by Index() and Value().
    58  // Modifies the state of the iterator.
    59  func (iterator *Iterator) First() bool {
    60  	iterator.Begin()
    61  	return iterator.Next()
    62  }