Skip to content

One-level options with default values and validation

Notifications You must be signed in to change notification settings

vitalets/flat-options

Repository files navigation

flat-options

Build Status npm license

One-level options with default values and validation

Utility function to merge simple one-level options with default values and perform validation.

Comparison to Object.assign

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"!

Comparison to other packages

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

Installation

npm install --save flat-options

Usage

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} 

License

MIT @ Vitaliy Potapov

Sponsor this project

 

Packages

No packages published