Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

on patched console if the first parameter is a string, it should treat it like an sprintf expression #111

Open
trajano opened this issue Oct 24, 2024 · 1 comment

Comments

@trajano
Copy link

trajano commented Oct 24, 2024

https://developer.mozilla.org/en-US/docs/Web/API/console#using_string_substitutions specifies that console would do something like sprintf but the patched console does not appear to do that.

@trajano
Copy link
Author

trajano commented Oct 24, 2024

Hopefully this would be of help, it's a simplistic sprintf operation

const sprintf = (format: string, ...args: any[]): string => {
  let i = 0;
  return format.replace(/%([sdif]|%\.\d+f|o|O)/g, (match: string): string => {
    if (i >= args.length) return match;

    switch (match) {
      case '%s':
        return String(args[i++]);
      case '%d':
      case '%i':
        return parseInt(args[i++], 10).toString();
      case '%f':
        return parseFloat(args[i++]).toString();
      case '%o':
      case '%O':
        return JSON.stringify(args[i++]);
      default: {
        const floatMatch = /^%\.(\d+)f$/.exec(match);
        if (floatMatch) {
          const precision = parseInt(floatMatch[1], 10);
          return parseFloat(args[i++]).toFixed(precision);
        }
        return match;
      }
    }
  });
};
export const consoleArgsToLoggerArgs = (...args: any[]): any[] => {
  if (args.length === 0) {
    return [];
  }
  if (typeof args[0] === 'string' && args[0].indexOf('%') !== -1) {
    const [format, ...subst] = args;
    return [sprintf(format, ...subst)];
  } else if (args[0] === undefined) {
    return ['undefined'];
  } else if (args[0] === null) {
    return ['null'];
  } else {
    return args;
  }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant