go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/nodes/pkg/incrutil/inputs.go (about) 1 /* 2 3 Copyright (c) 2023 - 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 "github.com/wcharczuk/go-incr" 11 12 // NewInputs returns an inputs collection for the given nodes. 13 func NewInputs[A any](nodes ...incr.Incr[A]) (output *Inputs[A]) { 14 output = new(Inputs[A]) 15 output.byInputNodeLabel = make(map[string]A) 16 output.inputs = make([]A, 0, len(nodes)) 17 for _, node := range nodes { 18 if node == nil { 19 continue 20 } 21 value := node.Value() 22 output.byInputNodeLabel[node.Node().Label()] = value 23 output.inputs = append(output.inputs, value) 24 } 25 return 26 } 27 28 // Inputs is a helper type to organize inputs to nodes for common functions like expressions. 29 type Inputs[A any] struct { 30 byInputNodeLabel map[string]A 31 inputs []A 32 } 33 34 // Values returns the underlying array of values. 35 func (i Inputs[A]) Values() []A { 36 return i.inputs 37 } 38 39 // ByIndex gets the input by index e.g. when it was added to the inputs list. 40 func (i Inputs[A]) ByIndex(index int) (value A, ok bool) { 41 if index < 0 || index >= len(i.inputs) { 42 return 43 } 44 return i.inputs[index], true 45 } 46 47 // ByNodeLabel returns the input by the label of the node it was sourced from. 48 func (i Inputs[A]) ByNodeLabel(nodeLabel string) (value A, ok bool) { 49 if i.byInputNodeLabel == nil { 50 return 51 } 52 value, ok = i.byInputNodeLabel[nodeLabel] 53 return 54 }