prefixsearch

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2023 License: GPL-2.0 Imports: 2 Imported by: 0

README

prefixsearch Go Reference

Golang string prefix search (for autocomplete)

go get -u github.com/ringsaturn/prefixsearch

Documentation

Overview

Package prefixsearch implements simple tree-based prefix search that i'm using for different web autocomplete services

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type SearchTree

type SearchTree[T comparable] struct {
	// contains filtered or unexported fields
}

SearchTree is struct to handle search tree

func New

func New[T comparable]() *SearchTree[T]

New creates new search tree

func (*SearchTree[T]) Add

func (tree *SearchTree[T]) Add(key string, value T)

Add one leaf to tree

func (*SearchTree[T]) AutoComplete

func (tree *SearchTree[T]) AutoComplete(prefix string) []T

AutoComplete returns autocomplete suggestions for given prefix

Example

ExampleAutoComplete just creates an object and does simple test

package main

import (
	"fmt"
	"sort"

	"github.com/ringsaturn/prefixsearch"
)

func main() {
	st := prefixsearch.New[int]()
	st.Add("Hello world!", 1)
	st.Add("New impressions", 2)
	st.Add("Hello golang!", 3)
	st.Add("Привет, мир!", 4)
	st.Add("Надо же :)", 5)

	intResult := st.AutoComplete("HE")

	sort.Ints(intResult)
	fmt.Println(intResult)
}
Output:
[1 3]
Example (Unicode)

Support of unicode symbols and using struct as value

package main

import (
	"fmt"

	"github.com/ringsaturn/prefixsearch"
)

type Item struct {
	ID      int
	Name    string
	Comment string
}

func (i *Item) LessThan(j Item) bool { return i.ID < j.ID }
func (i *Item) EqualTo(j Item) bool  { return i.ID == j.ID }

func main() {

	data := []Item{
		{1, "Hello world!", "First example"},
		{2, "New impressions", "Second example"},
		{3, "Hello golang!", "Some other important info"},
		{4, "Привет, мир!", "Unicode symbols also work"},
		{5, "こんにちは世界", "Even this one may work"},
	}

	st := prefixsearch.New[Item]()
	for _, x := range data {
		st.Add(x.Name, x)
	}

	fmt.Println(st.AutoComplete("こん"))
}
Output:
[{5 こんにちは世界 Even this one may work}]

func (*SearchTree[T]) Search

func (tree *SearchTree[T]) Search(key string) T

Search searches for value of key

Example

ExampleSearch shows another possible usage of this package

package main

import (
	"fmt"

	"github.com/ringsaturn/prefixsearch"
)

func main() {
	st := prefixsearch.New[int]()
	st.Add("Hello world!", 1)
	st.Add("New impressions", 2)
	st.Add("Hello golang!", 3)
	st.Add("Привет, мир!", 4)
	st.Add("Надо же :)", 5)

	fmt.Println(st.Search("HE"))
	fmt.Println(st.Search("HELLO WORLD"))
	fmt.Println(st.Search("HELLO WORLD!"))
	fmt.Println(st.Search("HELLO WORLD!!"))

}
Output:
0
0
1
0

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL