export function serializeData()

in packages/graph-explorer/src/core/StateProvider/serializeData.ts [25:56]


export function serializeData(data: any): any {
  if (data instanceof Date) {
    // Wrap dates in an object describing the type and convert to string
    return { __type: "Date", value: data.toISOString() };
  } else if (data instanceof Map) {
    // Wrap maps in an object describing the type and convert to array of array
    return {
      __type: "Map",
      value: Array.from(data.entries()).map(([key, value]) => [
        key,
        serializeData(value),
      ]),
    };
  } else if (data instanceof Set) {
    // Wrap sets in an object describing the type and convert to array of array
    return {
      __type: "Set",
      value: Array.from(data.values()).map(value => serializeData(value)),
    };
  } else if (Array.isArray(data)) {
    // Recursively serialize array items
    return data.map(serializeData);
  } else if (typeof data === "object" && data !== null) {
    // Recursively serialize object values
    return Object.fromEntries(
      Object.entries(data).map(([key, value]) => [key, serializeData(value)])
    );
  } else {
    // Must be a literal type that serializes fine on its own
    return data;
  }
}