示例工程 26-svelte5-runes

26-svelte5-runes/demo-02-snapshot/snapshot.ts

typescript · 1.4 KB

type JsonValue =
  string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };

function snapshot<T>(value: T): T {
  if (Array.isArray(value)) {
    return value.map((item) => snapshot(item)) as T;
  }
  if (value !== null && typeof value === "object") {
    const result: Record<string, unknown> = {};
    for (const [key, item] of Object.entries(value)) {
      result[key] = snapshot(item);
    }
    return result as T;
  }
  return value;
}

const original: JsonValue = {
  id: 7,
  tags: ["build", "network"],
  meta: { level: "info", nested: { ok: true } },
};

const copy = snapshot(original);
const isolated = copy !== original;
const nestedIsolated =
  typeof copy === "object" &&
  copy !== null &&
  !Array.isArray(copy) &&
  copy.meta !== (original as { meta: unknown }).meta;

if (typeof copy === "object" && copy !== null && !Array.isArray(copy)) {
  copy.id = 8;
  copy.tags = ["changed"];
}

const originalUntouched =
  typeof original === "object" &&
  original !== null &&
  !Array.isArray(original) &&
  original.id === 7 &&
  Array.isArray(original.tags) &&
  original.tags[0] === "build";

const roundTrip =
  JSON.stringify(snapshot(original)) === JSON.stringify(original);

console.log(
  JSON.stringify({
    evt: "smoke",
    ok: isolated && nestedIsolated && originalUntouched && roundTrip,
    isolated,
    nestedIsolated,
    originalUntouched,
    roundTrip,
    copy,
  }),
);