helpers.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. /*
  3. this seems to be not only shorter, but faster than
  4. string.replace(/\\/g, '\\\\').
  5. replace(/\u0008/g, '\\b').
  6. replace(/\t/g, '\\t').
  7. replace(/\n/g, '\\n').
  8. replace(/\f/g, '\\f').
  9. replace(/\r/g, '\\r').
  10. replace(/'/g, '\\\'').
  11. replace(/"/g, '\\"');
  12. or string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
  13. see http://jsperf.com/string-escape-regexp-vs-json-stringify
  14. */
  15. function srcEscape(str) {
  16. return JSON.stringify({
  17. [str]: 1
  18. }).slice(1, -3);
  19. }
  20. exports.srcEscape = srcEscape;
  21. let highlightFn;
  22. let cardinalRecommended = false;
  23. try {
  24. highlightFn = require('cardinal').highlight;
  25. } catch (err) {
  26. highlightFn = text => {
  27. if (!cardinalRecommended) {
  28. // eslint-disable-next-line no-console
  29. console.log('For nicer debug output consider install cardinal@^2.0.0');
  30. cardinalRecommended = true;
  31. }
  32. return text;
  33. };
  34. }
  35. /**
  36. * Prints debug message with code frame, will try to use `cardinal` if available.
  37. */
  38. function printDebugWithCode(msg, code) {
  39. // eslint-disable-next-line no-console
  40. console.log(`\n\n${msg}:\n`);
  41. // eslint-disable-next-line no-console
  42. console.log(`${highlightFn(code)}\n`);
  43. }
  44. exports.printDebugWithCode = printDebugWithCode;