github.com/MontFerret/ferret@v0.18.0/pkg/drivers/common/iterator.go (about)

     1  package common
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/MontFerret/ferret/pkg/drivers"
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  )
    10  
    11  type Iterator struct {
    12  	node drivers.HTMLElement
    13  	pos  values.Int
    14  }
    15  
    16  func NewIterator(
    17  	node drivers.HTMLElement,
    18  ) (core.Iterator, error) {
    19  	if node == nil {
    20  		return nil, core.Error(core.ErrMissedArgument, "result")
    21  	}
    22  
    23  	return &Iterator{node, 0}, nil
    24  }
    25  
    26  func (iterator *Iterator) Next(ctx context.Context) (value core.Value, key core.Value, err error) {
    27  	if iterator.node.Length() > iterator.pos {
    28  		idx := iterator.pos
    29  		val, err := iterator.node.GetChildNode(ctx, idx)
    30  
    31  		if err != nil {
    32  			return values.None, values.None, err
    33  		}
    34  
    35  		iterator.pos++
    36  
    37  		return val, idx, nil
    38  	}
    39  
    40  	return values.None, values.None, core.ErrNoMoreData
    41  }