implementation.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package shortcuts
  3. import (
  4. "fmt"
  5. )
  6. var _ = fmt.Print
  7. func (self *ShortcutMap[T]) first_action() (ans T) {
  8. for _, ac := range self.leaves {
  9. return ac
  10. }
  11. for _, child := range self.children {
  12. return child.first_action()
  13. }
  14. return
  15. }
  16. func (self *ShortcutMap[T]) shortcut_for(ac T) (keys []string) {
  17. keys = []string{}
  18. for key, q := range self.leaves {
  19. if ac == q {
  20. return append(keys, key)
  21. }
  22. }
  23. for key, child := range self.children {
  24. ckeys := child.shortcut_for(ac)
  25. if len(ckeys) > 0 {
  26. return append(append(keys, key), ckeys...)
  27. }
  28. }
  29. return
  30. }
  31. func (self *ShortcutMap[T]) add(ac T, keys []string) (conflict T) {
  32. sm := self
  33. last := len(keys) - 1
  34. for i, key := range keys {
  35. if i == last {
  36. if c, found := sm.leaves[key]; found {
  37. conflict = c
  38. }
  39. sm.leaves[key] = ac
  40. if c, found := sm.children[key]; found {
  41. conflict = c.first_action()
  42. delete(sm.children, key)
  43. }
  44. } else {
  45. if c, found := sm.leaves[key]; found {
  46. conflict = c
  47. delete(sm.leaves, key)
  48. }
  49. q := sm.children[key]
  50. if q == nil {
  51. q = &ShortcutMap[T]{leaves: map[string]T{}, children: map[string]*ShortcutMap[T]{}}
  52. sm.children[key] = q
  53. }
  54. sm = q
  55. }
  56. }
  57. return
  58. }