One-level options with default values and validation
Utility function to merge simple one-level options with default values and perform validation.
Benefits over Object.assign
are:
-
exclude of
undefined
values (useful for conditional options):const defaults = {foo: 'bar'}; const options = {foo: undefined}; Object.assign({}, defaults, options); // -> {foo: undefined} // vs flatOptions(options, defaults); // -> {foo: 'bar'}
-
validation of options keys:
const defaults = {foo: 'bar'}; const options = {unknown: 'baz'}; Object.assign({}, defaults, options); // -> {foo: 'bar', unknown: 'baz'} // vs flatOptions(options, defaults); // -> throws error "Unknown option"!
Benefits over existing defaults, lodash.defaults and object.defaults are:
- auto-validation of options keys
- zero dependencies
Note that this package is only for one-level options, for nested ones please use alternative packages
npm install --save flat-options
import flatOptions from 'flat-options';
const defaults = {
a: 1,
b: false
};
class Foo {
constructor(options) {
this._options = flatOptions(options, defaults);
}
}
const foo = new Foo({a: 2}); // foo._options will be {a: 2, b: false}
MIT @ Vitaliy Potapov