Created
June 28, 2023 14:40
-
-
Save abdivasiyev/d54a74cb834606983085e11defe65115 to your computer and use it in GitHub Desktop.
Simple ternary operator implementation in Go with generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ternary | |
type operatorIf[T comparable] struct { | |
condition bool | |
value T | |
elseIf *operatorIf[T] | |
elseValue T | |
} | |
func If[T comparable](condition bool) *operatorIf[T] { | |
return &operatorIf[T]{condition: condition} | |
} | |
func (i *operatorIf[T]) ElseIf(condition bool, value T) *operatorIf[T] { | |
curr := i | |
for curr.elseIf != nil { | |
curr = curr.elseIf | |
} | |
curr.elseIf = If[T](condition).Then(value) | |
return i | |
} | |
func (i *operatorIf[T]) Then(value T) *operatorIf[T] { | |
i.value = value | |
return i | |
} | |
func (i *operatorIf[T]) Else(value T) *operatorIf[T] { | |
i.elseValue = value | |
for curr := i.elseIf; curr != nil; { | |
curr.Else(i.elseValue) | |
curr = curr.elseIf | |
} | |
return i | |
} | |
func (i *operatorIf[T]) Exec() T { | |
println(i.condition, i.value, i.elseValue) | |
switch { | |
case !i.condition && i.elseIf != nil: | |
return i.elseIf.Exec() | |
case i.condition: | |
return i.value | |
default: | |
return i.elseValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment