leumas-universal-preset
Version:
A microservice to declare universal functions packed with reusable props via preset mappings.
61 lines (59 loc) • 2.44 kB
JavaScript
/**
* withPreset
*
* Wraps any function with a set of default properties (preset).
*
* Supports:
* 1. Options Object Mode: For functions expecting a single object, the preset object is merged with runtime options.
* 2. Positional Mode: For functions using positional parameters, you can supply:
* - A preset array of default values, or
* - A mapping object indicating which parameter indices should be filled from the preset.
*
* @param {Function} fn - The target function.
* @param {Object|Array} preset - An object (for options mode) or an array (for positional mode).
* @param {Object} options - Optional configuration. Supported key: mapping.
* mapping: an object mapping preset keys to parameter indices.
* @returns {Function} - A new function that merges the preset with provided arguments.
*/
function withPreset(fn, preset, options = {}) {
// If a mapping is provided, use it for positional merging.
if (options.mapping) {
return function(...args) {
const mergedArgs = [...args];
for (const [key, index] of Object.entries(options.mapping)) {
// Only use the preset if the argument at that index is undefined.
if (mergedArgs[index] === undefined && preset[key] !== undefined) {
mergedArgs[index] = preset[key];
}
}
return fn(...mergedArgs);
};
} else {
return function(...args) {
// Options object mode: merge if a single object is passed.
if (
args.length === 1 &&
typeof args[0] === 'object' &&
!Array.isArray(args[0]) &&
typeof preset === 'object' &&
!Array.isArray(preset)
) {
const finalOptions = { ...preset, ...args[0] };
return fn(finalOptions);
} else if (Array.isArray(preset)) {
// Positional array mode.
const mergedArgs = preset.map((defaultVal, i) =>
i < args.length && args[i] !== undefined ? args[i] : defaultVal
);
if (args.length > preset.length) {
mergedArgs.push(...args.slice(preset.length));
}
return fn(...mergedArgs);
} else {
// Fallback: simply call the function with runtime arguments.
return fn(...args);
}
};
}
}
module.exports = { withPreset };