johnloy
10/3/2018 - 1:48 PM

Stringify JSON Including Function Bodies

/* tslint:disable-next-line */
let stringifyObj = function (obj: object): any {};

if (!DEBUG) {
  stringifyObj = (obj: object): string => {
    const placeholder = "____PLACEHOLDER____";
    const fns: Function[] = [];
    let json = JSON.stringify(
      obj,
      function (_, value: any): any {
        if (typeof value === "function") {
          fns.push(value);
          return placeholder;
        }
        return value;
      },
      2
    );
    json = json.replace(new RegExp('"' + placeholder + '"', "g"), (_): string =>
      fns.shift()!.toString()
    );
    return json;
  };
}

export default stringifyObj;