I wrote this shortcode parsing and it runs in \$O(N^2)\$. Is there a way to better optimize this?
package shortcodes
import (
"regexp"
"strings"
)
var (
shortcodesRegex = regexp.MustCompile(`\[\S+(?:\s+[^="]+(|="[^"\]\s]+"))+\]`)
)
func Parse(content string) []map[string]string {
results := make([]map[string]string, 0)
indexes := shortcodesRegex.FindAllIndex([]byte(content), -1)
for _, matches := range indexes {
result := make(map[string]string)
shortcode := string(content[matches[0]+1 : matches[1]-1])
parts := strings.Fields(shortcode)
for i, part := range parts {
if i == 0 {
result["id"] = part
continue
}
pair := strings.Split(part, "=")
if len(pair) > 1 {
result[pair[0]] = pair[1][1 : len(pair[1])-1]
} else {
result[pair[0]] = ""
}
}
results = append(results, result)
}
return results
}
Here is one of the test cases I have written.
{
name: "basic",
args: args{`First shortcode is [fraction num="1" denom="2"] and the second is [square-root content="456"] which we will pass into a function which will return these IDs and all their values in a map`},
want: []map[string]string{
{
"id": "fraction",
"num": "1",
"denom": "2",
},
{
"id": "square-root",
"content": "456",
},
},
},