go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/nodes/pkg/funcs/index.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 funcs 9 10 import ( 11 "context" 12 "fmt" 13 14 "go.charczuk.com/projects/nodes/pkg/incrutil" 15 "go.charczuk.com/sdk/iter" 16 ) 17 18 func First[T any](ctx context.Context, inputs *incrutil.Inputs[T]) (output T, err error) { 19 return elementIndexMany[T](ctx, 0, inputs.Values()...) 20 } 21 22 func FirstMany[T any](ctx context.Context, inputs *incrutil.Inputs[[]T]) (output T, err error) { 23 return elementIndexManySlice[T](ctx, 0, inputs.Values()...) 24 } 25 26 func Last[T any](ctx context.Context, inputs *incrutil.Inputs[T]) (output T, err error) { 27 values := inputs.Values() 28 return elementIndexMany[T](ctx, len(values)-1, values...) 29 } 30 31 func LastMany[T any](_ context.Context, inputs *incrutil.Inputs[[]T]) (output T, err error) { 32 values := inputs.Values() 33 merged := iter.MergeMany[T](values) 34 if len(merged) == 0 { 35 return 36 } 37 output = merged[len(merged)-1] 38 return 39 } 40 41 func elementIndexMany[T any](_ context.Context, index int, values ...T) (output T, err error) { 42 if len(values) == 0 { 43 return 44 } 45 if index < 0 || index >= len(values) { 46 err = fmt.Errorf("index out of range: %d", index) 47 return 48 } 49 output = values[index] 50 return 51 } 52 53 func elementIndexManySlice[T any](_ context.Context, index int, values ...[]T) (output T, err error) { 54 merged := iter.MergeMany[T](values) 55 if len(merged) == 0 { 56 return 57 } 58 if index < 0 || index >= len(merged) { 59 err = fmt.Errorf("index out of range: %d", index) 60 return 61 } 62 output = merged[index] 63 return 64 }