Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 23x 23x 23x 23x 23x 5x 5x 5x 5x 5x 23x 23x 23x 18x 18x 18x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x | import { type TeamContract, type TeamTreeNode } from '@amalia/tenants/teams/types';
/**
* Create a team tree from a flat list of teams.
* This method allows use to add custom properties to each tree node.
*
* BE CAREFUL WHEN USING THIS FUNCTION. If you try to map its nodes afterwards, it will not work as expected because it uses the refs of tree nodes.
* You cannot use the result of this function to pass data from server to client or from client to server, because you will get a circular reference error when trying to serialize.
*
* @param teams The list of teams to create the tree from.
* @param mapTeamNode A function that receives a partial team node and returns a full team node. This mapping is done before setting parents and children so you cannot use them.
*/
export function makeEnhancedTeamsTree<
TTeam extends Pick<TeamContract, 'id' | 'parentTeamId'>,
TTeamTreeNode extends TeamTreeNode<TTeam> = TeamTreeNode<TTeam>,
>(teams: TTeam[], mapTeamNode: (partialTeam: TeamTreeNode<TTeam>) => TTeamTreeNode): TTeamTreeNode[] {
const teamsTree = teams.map((team) =>
mapTeamNode({
team,
children: [],
parent: undefined,
}),
);
// For each node, find its parent and add it as a child.
// We are mutating here because we are using the references created above.
teamsTree.forEach((teamNode) => {
const parentTeam = teamsTree.find((t) => t.team.id === teamNode.team.parentTeamId);
if (parentTeam) {
teamNode.parent = parentTeam;
parentTeam.children.push(teamNode);
}
});
return teamsTree;
}
/**
* Create a team tree from a flat list of teams.
* This method is the simpler version, where you get a result of team/children/parent tree nodes.
*
* BE CAREFUL WHEN USING THIS FUNCTION. If you try to map its nodes afterwards, it will not work as expected because it uses the refs of tree nodes.
* You cannot use the result of this function to pass data from server to client or from client to server, because you will get a circular reference error when trying to serialize.
*/
export function makeTeamsTree<TTeam extends Pick<TeamContract, 'id' | 'parentTeamId'>>(
teams: TTeam[],
): TeamTreeNode<TTeam>[] {
return makeEnhancedTeamsTree(teams, (teamNode) => teamNode);
}
|