Source: interpolation.js

  1. const errors = require('./errors');
  2. /**
  3. * Regular Expression to match placeholders.
  4. * @type {RegExp}
  5. * @private
  6. */
  7. const PLACEHOLDER = new RegExp(/%\(([\w-]+)\)s/);
  8. /**
  9. * Maximum recursion depth for parseValue
  10. * @type {number}
  11. */
  12. const MAXIMUM_INTERPOLATION_DEPTH = 50;
  13. /**
  14. * Recursively parses a string and replaces the placeholder ( %(key)s )
  15. * with the value the key points to.
  16. * @param {ParserConfig} parser - Parser Config Object
  17. * @param {string} section - Section Name
  18. * @param {string} key - Key Name
  19. */
  20. function interpolate(parser, section, key) {
  21. return interpolateRecurse(parser, section, key, 1);
  22. }
  23. /**
  24. * Interpolate Recurse
  25. * @param parser
  26. * @param section
  27. * @param key
  28. * @param depth
  29. * @private
  30. */
  31. function interpolateRecurse(parser, section, key, depth) {
  32. let value = parser.get(section, key, true);
  33. if(depth > MAXIMUM_INTERPOLATION_DEPTH){
  34. throw new errors.MaximumInterpolationDepthError(section, key, value, MAXIMUM_INTERPOLATION_DEPTH);
  35. }
  36. let res = PLACEHOLDER.exec(value);
  37. while(res !== null){
  38. const placeholder = res[1];
  39. const rep = interpolateRecurse(parser, section, placeholder, depth + 1);
  40. // replace %(key)s with the returned value next
  41. value = value.substr(0, res.index) + rep +
  42. value.substr(res.index + res[0].length);
  43. // get next placeholder
  44. res = PLACEHOLDER.exec(value);
  45. }
  46. return value;
  47. }
  48. module.exports = {
  49. interpolate,
  50. MAXIMUM_INTERPOLATION_DEPTH
  51. };