iterator.go 961 B

123456789101112131415161718192021222324252627282930313233343536
  1. package jsc
  2. import "github.com/dop251/goja"
  3. type Iterator[M Module, T any] struct {
  4. c Class[M, *Iterator[M, T]]
  5. values []T
  6. block func(this T) any
  7. }
  8. func NewIterator[M Module, T any](class Class[M, *Iterator[M, T]], values []T, block func(this T) any) goja.Value {
  9. return class.New(&Iterator[M, T]{class, values, block})
  10. }
  11. func CreateIterator[M Module, T any](module M) Class[M, *Iterator[M, T]] {
  12. class := NewClass[M, *Iterator[M, T]](module)
  13. class.DefineMethod("next", (*Iterator[M, T]).next)
  14. class.DefineMethod("toString", (*Iterator[M, T]).toString)
  15. return class
  16. }
  17. func (i *Iterator[M, T]) next(call goja.FunctionCall) any {
  18. result := i.c.Runtime().NewObject()
  19. if len(i.values) == 0 {
  20. result.Set("done", true)
  21. } else {
  22. result.Set("done", false)
  23. result.Set("value", i.block(i.values[0]))
  24. i.values = i.values[1:]
  25. }
  26. return result
  27. }
  28. func (i *Iterator[M, T]) toString(call goja.FunctionCall) any {
  29. return "[sing-box Iterator]"
  30. }