go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/nodes/pkg/funcs/min_max.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  	"cmp"
    12  	"context"
    13  
    14  	"go.charczuk.com/projects/nodes/pkg/incrutil"
    15  )
    16  
    17  func Min[T cmp.Ordered](ctx context.Context, inputValues *incrutil.Inputs[T]) (output T, _ error) {
    18  	inputs := inputValues.Values()
    19  	if len(inputs) == 0 {
    20  		return
    21  	}
    22  	output = inputs[0]
    23  	for _, i := range inputs[1:] {
    24  		if i < output {
    25  			output = i
    26  		}
    27  	}
    28  	return
    29  }
    30  
    31  func MinMany[T cmp.Ordered](ctx context.Context, inputValues *incrutil.Inputs[[]T]) (output T, _ error) {
    32  	inputs := inputValues.Values()
    33  	var didSetOutput bool
    34  	for _, values := range inputs {
    35  		for _, i := range values {
    36  			if !didSetOutput {
    37  				output = i
    38  				didSetOutput = true
    39  				continue
    40  			}
    41  			if i < output {
    42  				output = i
    43  			}
    44  		}
    45  	}
    46  	return
    47  }
    48  
    49  func Max[T cmp.Ordered](ctx context.Context, inputValues *incrutil.Inputs[T]) (output T, _ error) {
    50  	inputs := inputValues.Values()
    51  	if len(inputs) == 0 {
    52  		return
    53  	}
    54  	output = inputs[0]
    55  	for _, i := range inputs[1:] {
    56  		if i > output {
    57  			output = i
    58  		}
    59  	}
    60  	return
    61  }
    62  
    63  func MaxMany[T cmp.Ordered](ctx context.Context, inputValues *incrutil.Inputs[[]T]) (output T, _ error) {
    64  	inputs := inputValues.Values()
    65  
    66  	var didSetOutput bool
    67  	for _, values := range inputs {
    68  		for _, i := range values {
    69  			if !didSetOutput {
    70  				output = i
    71  				didSetOutput = true
    72  				continue
    73  			}
    74  			if i > output {
    75  				output = i
    76  			}
    77  		}
    78  	}
    79  	return
    80  }