I have two structs, Employee and Project.
type Employee struct {
ID int
Projects map[*Departments]struct{}
}
type Project struct {
ID int
}
I have a Company struct that has the following:
type Company struct {
Projects map[*Project]map[*Employee]struct{}
Employees map[*Employee]struct{}
}
Given e *Employee
and c *Company
(func (c *Company) getEmployeesOnSameProject(e *Employee) []*Employee { }
)and knowing that an employee can belong to multiple projects, I am having a difficult time figuring out how to get the employees across projects.
e.Projects
might be something like -
eProjects {
P1
P2
}
c.Projects
might be something like -
cProjects {
P1 {
E1
E2
}
P2 {
E1
E2
E3
E4
}
}
If I am E1, how can I easily get the other employees on the same projects (P1 and P2) as me without having a nested for loop?
If I understand correctly, in an idea world you'd like to be able to lookup "employees for a given project" as well as "projects for a given employee"?
Without knowing the context that you will be using this code in; e.g. more writes than reads, more reads than writes, what the space vs. time complexity requirements are.
If you are aiming for O(1) lookup for projects for an employee and O(1) lookup for employees for a project, then I would suggest creating your own datastructure to be able to facilitate this. This is the smallest interface that would work:
type ProjectEmployees interface {
RegisterProjectEmployee(p *Project, e *Employee)
GetEmployees(p *Project) []*Employees
GetProjects(e *Employee) []*Project
}
I haven't listed a full implementation below as it would be trivial to work out, but you'd implement this interface with a struct that store 2 maps.
The tradeoff is that you have a larger write / update cost, and data duplication, the benefit is O(1) lookups in both directions Project <--> Employee
.
type projecEmployeesMap struct {
pe map[*Project][]*Employee
ep map[*Employee][]*Project
}
func (p *projectEmployeesMap) RegisterProjectEmployee(p *Project, e *Employee) {
p.pe[p] = append(p.pe[p], e) // store the mapping project -> employees
p.ep[e] = append(p.ep[e], p) // store the mapping employees --> project
}
The get methods should be easy to implement with simple map lookups