1. /**
  2. * Matches configuration patterns using a simple rule-based system.
  3. *
  4. * @param {object} config The configuration object to validate.
  5. * @param {array} patterns An array of configuration patterns. Each pattern
  6. * is an object with a `key` and a `pattern` property.
  7. * `pattern` can be a string (exact match) or a function
  8. * that takes the config object as input and returns true
  9. * if the pattern matches, false otherwise.
  10. * @returns {object} An object containing the matched patterns and any errors.
  11. */
  12. function matchConfigPatterns(config, patterns) {
  13. const matches = {};
  14. const errors = [];
  15. for (const pattern of patterns) {
  16. const { key, pattern: patternFn } = pattern;
  17. try {
  18. if (typeof patternFn === 'function') {
  19. if (patternFn(config)) {
  20. matches[key] = patternFn;
  21. }
  22. } else if (typeof patternFn === 'string') {
  23. if (config.hasOwnProperty(key) && config[key] === patternFn) {
  24. matches[key] = patternFn;
  25. }
  26. } else {
  27. errors.push(`Invalid pattern type for key ${key}. Expected string or function.`);
  28. }
  29. } catch (err) {
  30. errors.push(`Error matching pattern for key ${key}: ${err.message}`);
  31. }
  32. }
  33. return { matches, errors };
  34. }

Add your comment