Code.mjs 722 B

1234567891011121314151617181920212223242526272829
  1. /**
  2. * Code resources.
  3. *
  4. * @author n1474335 [n1474335@gmail.com]
  5. * @copyright Crown Copyright 2018
  6. * @license Apache-2.0
  7. */
  8. /**
  9. * This tries to rename variable names in a code snippet according to a function.
  10. *
  11. * @param {string} input
  12. * @param {function} replacer - This function will be fed the token which should be renamed.
  13. * @returns {string}
  14. */
  15. export function replaceVariableNames(input, replacer) {
  16. const tokenRegex = /\\"|"(?:\\"|[^"])*"|(\b[a-z0-9\-_]+\b)/ig;
  17. return input.replace(tokenRegex, (...args) => {
  18. const match = args[0],
  19. quotes = args[1];
  20. if (!quotes) {
  21. return match;
  22. } else {
  23. return replacer(match);
  24. }
  25. });
  26. }