go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/nodes/pkg/incrutil/func.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package incrutil
     9  
    10  import (
    11  	"context"
    12  
    13  	"github.com/wcharczuk/go-incr"
    14  )
    15  
    16  // Func is a node that runs a function for every stabilization pass.
    17  func Func[Output any](scope incr.Scope, fn Funcfn[Output]) FuncIncr[Output] {
    18  	return incr.WithinScope(scope, &funcIncr[Output]{
    19  		n:  incr.NewNode("func"),
    20  		fn: fn,
    21  	})
    22  }
    23  
    24  type Funcfn[Output any] func(context.Context) (Output, error)
    25  
    26  type FuncIncr[Output any] interface {
    27  	incr.AlwaysIncr[Output]
    28  }
    29  
    30  type funcIncr[Output any] struct {
    31  	n   *incr.Node
    32  	fn  Funcfn[Output]
    33  	val Output
    34  }
    35  
    36  func (f *funcIncr[Output]) Node() *incr.Node {
    37  	return f.n
    38  }
    39  
    40  func (f *funcIncr[Output]) Stabilize(ctx context.Context) error {
    41  	newVal, err := f.fn(ctx)
    42  	if err != nil {
    43  		return err
    44  	}
    45  	f.val = newVal
    46  	return nil
    47  }
    48  
    49  func (f *funcIncr[Output]) Value() Output { return f.val }
    50  
    51  func (f *funcIncr[Output]) RawValue() any {
    52  	return f.val
    53  }
    54  
    55  func (f *funcIncr[Output]) Always() {}
    56  
    57  func (f *funcIncr[Output]) String() string {
    58  	return f.n.String()
    59  }