Skip to content

Instantly share code, notes, and snippets.

@nijynot
Created February 12, 2025 18:52
Show Gist options
  • Save nijynot/cd485b150ce259241ab6615f1eb3b245 to your computer and use it in GitHub Desktop.
Save nijynot/cd485b150ce259241ab6615f1eb3b245 to your computer and use it in GitHub Desktop.
bson.ts
export default class BSON {
  static stringify(value: string, space?: string | number) {
    return JSON.stringify(value, replacer, space);
  }

  static parse(text: string) {
    return JSON.parse(text, reviver);
  }
}

function replacer(key: string, value: any) {
  if (typeof value === "bigint") {
    return value.toString() + 'n';
  }
  return value;
}

function reviver(key: string, value: any) {
  if (typeof value === 'string' && /^\d+n$/.test(value)) {
    return BigInt(value.slice(0, -1));
  }
  return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment