Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 36 lines · 1.3 KiB · at 358de06

import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable } from "@tsus/runtime/boundary";export type User = { id: string; name: string; managerId: Option<string>; email: Option<string> };export type ChainError = { kind: "unknown_user" | "cycle"; id: string };const indexById = (users: readonly User[]): Map<string, User> => {  const byId = new Map<string, User>();  for (const u of users) {    if (!byId.has(u.id)) {      byId.set(u.id, u);    }  }  return byId;};const usableEmail = (u: User): Option<string> => u.email.andThen((e) => (e !== "" ? Some(e) : None));const walk = (byId: Map<string, User>, next: Option<string>, reached: Set<string>): Result<Option<string>, ChainError> =>  match (next.andThen((id) => fromNullable(byId.get(id)))) {    None => Ok(None),    Some(m) => reached.has(m.id)      ? Err({ kind: "cycle", id: m.id })      : usableEmail(m).isSome()        ? Ok(usableEmail(m))        : walk(byId, m.managerId, new Set([...reached, m.id])),  };export const escalationEmail = (users: readonly User[], userId: string): Result<Option<string>, ChainError> => {  const byId = indexById(users);  return match (fromNullable(byId.get(userId))) {    None => Err({ kind: "unknown_user", id: userId }),    Some(start) => walk(byId, start.managerId, new Set([start.id])),  };};