utilities.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package node
  2. // Delete an item from an array, returning item and true on success.
  3. func arrayDelete[T any](stack *[]T, pos int) (T, bool) {
  4. // log.Printf("Array %d, %d\n", len(*stack), cap(*stack))
  5. var result T
  6. /*
  7. https://stackoverflow.com/questions/33834742/remove-and-adding-elements-to-array-in-go-lang
  8. https://github.com/golang/go/wiki/SliceTricks
  9. */
  10. if pos < 0 || pos > len(*stack) {
  11. return result, false
  12. }
  13. result = (*stack)[pos]
  14. copy((*stack)[pos:], (*stack)[pos+1:])
  15. // var temp T
  16. // (*stack)[len(*stack)-1] = temp
  17. *stack = (*stack)[:len(*stack)-1]
  18. return result, true
  19. }
  20. // Pop items from head of array, return true on success.
  21. func arrayPop[T any](stack *[]T, count int) bool {
  22. /*
  23. https://stackoverflow.com/questions/33834742/remove-and-adding-elements-to-array-in-go-lang
  24. https://github.com/golang/go/wiki/SliceTricks
  25. */
  26. if count < 0 || count > len(*stack) {
  27. return false
  28. }
  29. copy((*stack)[0:], (*stack)[count:])
  30. // var temp T
  31. // (*stack)[len(*stack)-1] = temp
  32. *stack = (*stack)[:len(*stack)-count]
  33. return true
  34. }