/**
* Matches configuration patterns using a simple rule-based system.
*
* @param {object} config The configuration object to validate.
* @param {array} patterns An array of configuration patterns. Each pattern
* is an object with a `key` and a `pattern` property.
* `pattern` can be a string (exact match) or a function
* that takes the config object as input and returns true
* if the pattern matches, false otherwise.
* @returns {object} An object containing the matched patterns and any errors.
*/
function matchConfigPatterns(config, patterns) {
const matches = {};
const errors = [];
for (const pattern of patterns) {
const { key, pattern: patternFn } = pattern;
try {
if (typeof patternFn === 'function') {
if (patternFn(config)) {
matches[key] = patternFn;
}
} else if (typeof patternFn === 'string') {
if (config.hasOwnProperty(key) && config[key] === patternFn) {
matches[key] = patternFn;
}
} else {
errors.push(`Invalid pattern type for key ${key}. Expected string or function.`);
}
} catch (err) {
errors.push(`Error matching pattern for key ${key}: ${err.message}`);
}
}
return { matches, errors };
}
Add your comment