Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 34 lines · 1.2 KiB · at 8b87e58

// Plausible bug: truthiness checks on patch values (so "" is skipped, not rejected) and the input profile is mutated in place.export type Profile = { name: string; email?: string; phone?: string };export type ProfilePatch = { name?: string; email?: string | null; phone?: string | null };export class ProfileError extends Error {  constructor(public readonly kind: "invalid_name" | "invalid_email" | "invalid_phone") {    super(kind);  }}export function applyPatch(profile: Profile, patch: ProfilePatch): Profile {  const out = profile;  if (patch.name) {    if (!patch.name.trim()) throw new ProfileError("invalid_name");    out.name = patch.name.trim();  }  if (patch.email) {    const e = patch.email.trim();    const [local, domain, ...rest] = e.split("@");    if (!local || !domain || rest.length) throw new ProfileError("invalid_email");    out.email = e;  } else if (patch.email === null) {    delete out.email;  }  if (patch.phone) {    const p = patch.phone.trim();    const digits = p.replace(/\D/g, "").length;    if (!/^\+?[\d -]+$/.test(p) || digits < 7 || digits > 15) throw new ProfileError("invalid_phone");    out.phone = p;  } else if (patch.phone === null) {    delete out.phone;  }  return out;}