Skip to content

Instantly share code, notes, and snippets.

@slofurno
Created August 31, 2017 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slofurno/d34933993be6f171c9a818e51b77aa65 to your computer and use it in GitHub Desktop.
Save slofurno/d34933993be6f171c9a818e51b77aa65 to your computer and use it in GitHub Desktop.
package tree
import (
"github.com/Getsidecar/partner-api-gateway/models"
)
// Tree is a graph representation of an Adgroup's partitions
type Tree struct {
Partition models.AdGroupCriterion `json:"root"`
Partitions []*Tree `json:"partitions"`
OPP *Tree `json:"opp"`
AdGroupId int64 `json:"adgroup_id"`
ProductScopes []models.ProductCondition `json:"product_scopes"`
AttributeType string `json:"attribute_type"`
AttributeAdditionalType string `json:"attribute_additional_type"`
}
func isOPP(x models.AdGroupCriterion) bool {
return x.Criterion.Condition.Attribute == ""
}
func BuildTree(crits []models.AdGroupCriterion) *Tree {
var root *Tree
seen := make(map[int64]*Tree, len(crits))
for i := 0; i < len(crits); i++ {
seen[crits[i].Id] = &Tree{Partition: crits[i]}
}
for _, node := range seen {
//for i := 0; i < len(crits); i++ {
parent := node.Partition.Criterion.ParentCriterionId
if parent == 0 {
root = node
continue
}
if isOPP(node.Partition) {
seen[parent].OPP = node
} else {
seen[parent].Partitions = append(seen[parent].Partitions, node)
}
}
return root
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment