Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 31 lines · 1.1 KiB · at f30ac63

export type User = { id: string; name: string; managerId?: string; email?: string };export class ChainError extends Error {  constructor(    public readonly kind: "unknown_user" | "cycle",    public readonly id: string,  ) {    super(`${kind}: ${id}`);  }}/** The first non-empty email up the chain, or undefined if there is none. Throws ChainError. */export function escalationEmail(users: readonly User[], userId: string): string | undefined {  const byId = new Map<string, User>();  for (const u of users) {    if (!byId.has(u.id)) byId.set(u.id, u);  }  const start = byId.get(userId);  if (start === undefined) throw new ChainError("unknown_user", userId);  const reached = new Set<string>([start.id]);  let next = start.managerId;  while (next !== undefined && next !== null) {    const manager = byId.get(next);    if (manager === undefined) return undefined;    if (reached.has(manager.id)) throw new ChainError("cycle", manager.id);    if (typeof manager.email === "string" && manager.email !== "") return manager.email;    reached.add(manager.id);    next = manager.managerId;  }  return undefined;}