chars.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. var chars = {}, unesc, temp;
  3. function reverse(object, prepender) {
  4. return Object.keys(object).reduce(function(reversed, key) {
  5. var newKey = prepender ? prepender + key : key; // Optionally prepend a string to key.
  6. reversed[object[key]] = newKey; // Swap key and value.
  7. return reversed; // Return the result.
  8. }, {});
  9. }
  10. /**
  11. * Regex for common characters
  12. */
  13. chars.escapeRegex = {
  14. '?': /\?/g,
  15. '@': /\@/g,
  16. '!': /\!/g,
  17. '+': /\+/g,
  18. '*': /\*/g,
  19. '(': /\(/g,
  20. ')': /\)/g,
  21. '[': /\[/g,
  22. ']': /\]/g
  23. };
  24. /**
  25. * Escape characters
  26. */
  27. chars.ESC = {
  28. '?': '__UNESC_QMRK__',
  29. '@': '__UNESC_AMPE__',
  30. '!': '__UNESC_EXCL__',
  31. '+': '__UNESC_PLUS__',
  32. '*': '__UNESC_STAR__',
  33. ',': '__UNESC_COMMA__',
  34. '(': '__UNESC_LTPAREN__',
  35. ')': '__UNESC_RTPAREN__',
  36. '[': '__UNESC_LTBRACK__',
  37. ']': '__UNESC_RTBRACK__'
  38. };
  39. /**
  40. * Unescape characters
  41. */
  42. chars.UNESC = unesc || (unesc = reverse(chars.ESC, '\\'));
  43. chars.ESC_TEMP = {
  44. '?': '__TEMP_QMRK__',
  45. '@': '__TEMP_AMPE__',
  46. '!': '__TEMP_EXCL__',
  47. '*': '__TEMP_STAR__',
  48. '+': '__TEMP_PLUS__',
  49. ',': '__TEMP_COMMA__',
  50. '(': '__TEMP_LTPAREN__',
  51. ')': '__TEMP_RTPAREN__',
  52. '[': '__TEMP_LTBRACK__',
  53. ']': '__TEMP_RTBRACK__'
  54. };
  55. chars.TEMP = temp || (temp = reverse(chars.ESC_TEMP));
  56. module.exports = chars;