normalize_opts.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Convert input options to more useable format
  2. // and compile search regexp
  3. 'use strict';
  4. function quoteRE(str) {
  5. return str.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&');
  6. }
  7. module.exports = function normalize_opts(options) {
  8. var emojies = options.defs,
  9. shortcuts;
  10. // Filter emojies by whitelist, if needed
  11. if (options.enabled.length) {
  12. emojies = Object.keys(emojies).reduce(function (acc, key) {
  13. if (options.enabled.indexOf(key) >= 0) {
  14. acc[key] = emojies[key];
  15. }
  16. return acc;
  17. }, {});
  18. }
  19. // Flatten shortcuts to simple object: { alias: emoji_name }
  20. shortcuts = Object.keys(options.shortcuts).reduce(function (acc, key) {
  21. // Skip aliases for filtered emojies, to reduce regexp
  22. if (!emojies[key]) { return acc; }
  23. if (Array.isArray(options.shortcuts[key])) {
  24. options.shortcuts[key].forEach(function (alias) {
  25. acc[alias] = key;
  26. });
  27. return acc;
  28. }
  29. acc[options.shortcuts[key]] = key;
  30. return acc;
  31. }, {});
  32. // Compile regexp
  33. var names = Object.keys(emojies)
  34. .map(function (name) { return ':' + name + ':'; })
  35. .concat(Object.keys(shortcuts))
  36. .sort()
  37. .reverse()
  38. .map(function (name) { return quoteRE(name); })
  39. .join('|');
  40. var scanRE = RegExp(names);
  41. var replaceRE = RegExp(names, 'g');
  42. return {
  43. defs: emojies,
  44. shortcuts: shortcuts,
  45. scanRE: scanRE,
  46. replaceRE: replaceRE
  47. };
  48. };