github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/testdata/generics/value/value.go (about)

     1  package value
     2  
     3  type (
     4  	Value[T any] interface {
     5  		Get(Callback[T], Callback[T])
     6  	}
     7  
     8  	Callback[T any] func(T)
     9  
    10  	Transform[S any, D any] func(S) D
    11  )
    12  
    13  func New[T any](v T) Value[T] {
    14  	return &value[T]{
    15  		v: v,
    16  	}
    17  }
    18  
    19  type value[T any] struct {
    20  	v T
    21  }
    22  
    23  func (v *value[T]) Get(fn1, fn2 Callback[T]) {
    24  	// For example purposes.
    25  	// Normally would be asynchronous callback.
    26  	fn1(v.v)
    27  	fn2(v.v)
    28  }
    29  
    30  func Map[S, D any](v Value[S], tx Transform[S, D]) Value[D] {
    31  	return &mapper[S, D]{
    32  		v:  v,
    33  		tx: tx,
    34  	}
    35  }
    36  
    37  type mapper[S, D any] struct {
    38  	v  Value[S]
    39  	tx Transform[S, D]
    40  }
    41  
    42  func (m *mapper[S, D]) Get(fn1, fn2 Callback[D]) {
    43  	// two callbacks are passed to generate more than
    44  	// one anonymous function symbol name.
    45  	m.v.Get(func(v S) {
    46  		// anonymous function inside of anonymous function.
    47  		func() {
    48  			fn1(m.tx(v))
    49  		}()
    50  	}, func(v S) {
    51  		fn2(m.tx(v))
    52  	})
    53  }