Skip to content

Instantly share code, notes, and snippets.

@berryp
Created August 26, 2015 21:30
Show Gist options
  • Save berryp/79cdd477298914096f55 to your computer and use it in GitHub Desktop.
Save berryp/79cdd477298914096f55 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strings"
)
type CategoryList struct {
Categories []Category
}
func (cl CategoryList) GetCategory(id int) Category {
for _, cat := range cl.Categories {
if cat.Id == id {
return cat
}
}
return Category{}
}
type Category struct {
Name string
Id int
ParentId int
Slugs []string
}
func (cl CategoryList) CategorySlugs(c Category) []string {
slugs := []string{c.Name}
parentId := c.ParentId
for {
cat := cl.GetCategory(parentId)
if cat.Id == 0 {
break
}
parentId = cat.ParentId
slugs = append([]string{cat.Name}, slugs...)
}
return slugs
}
func (cl CategoryList) CategoryUrl(cat Category) string {
slugs := cl.CategorySlugs(cat)
return strings.Join(slugs, "/")
}
func main() {
cl := CategoryList{[]Category{
{"Clothing", 1, 0, []string{}},
{"Lingerie", 2, 0, []string{}},
{"Jackets", 3, 1, []string{}},
{"Shorts", 4, 1, []string{}},
{"Bras", 5, 2, []string{}},
{"Briefs", 6, 2, []string{}},
}}
for _, cat := range cl.Categories {
fmt.Println(cl.CategoryUrl(cat))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment