Skip to content

extended-library/optionist

Repository files navigation

optionist

GitHub Release Travis CI Coverage Status Greenkeeper Inline Docs

Code Style Guide Commit Style Guide Release Workflow ISC License PRs Welcome


A powerful options object parser utility, a.k.a. Options Specialist.

Follow the project on Twitter for updates and check out the contribution section if you're looking to contribute (issues, PRs, improve examples & docs, fix typos, discuss ideas, etc.).


Why optionist?

Installation

npm install optionist --save

Usage

Easy options Object Parsing

const optionist = require('optionist')

// with a dedicated defaults object --------------------------------------------
const DEFAULTS = { 
  value: 7, 
  flag: true, 
  callback: null
  /* etc. */
}

function testFuncion1 (options) {
  options = optionist(options, DEFAULTS)

  this._value = options.value
  this._flag = options.flag
  this._callback = options.callback  
}

testFunction1({ value: 42 })

// with inline defaults --------------------------------------------------------
function testFuncion2 (options) {
  options = optionist(options, { 
    value: 7, 
    flag: true, 
    callback: null
    /* etc. */
  })

  this._value = options.value
  this._flag = options.flag
  this._callback = options.callback
}

testFunction2({ value: 42 })

A Better Object.assign Alternative

// with underscored properties (e.g.: this._value = 42) ------------------------
const underscore = require('optionist/assign/underscore')

function testFuncion1 (options) {
  // the properties will be set automatically based on the options
  // that are merged with the passed options and with the default options
  underscore(options, DEFAULTS)  
  
  /*
    the following properties will be set automatically
    based on the options and default options:

     - this._value
     - this._flag
     - this._callback
  */

  this._value = options.value
  this._flag = options.flag
  this._callback = options.callback  
}

testFunction1({ value: 42 })




const optionist = require('optionist')

// with a dedicated defaults object --------------------------------------------
const DEFAULTS = { 
  value: 7, 
  flag: true, 
  callback: null
  /* etc. */
}

function testFuncion1 (options) {
  options = optionist(options, DEFAULTS)

  this._value = options.value
  this._flag = options.flag
  this._callback = options.callback  
}

testFunction1({ value: 42 })

// with inline defaults --------------------------------------------------------
function testFuncion2 (options) {
  options = optionist(options, { 
    value: 7, 
    flag: true, 
    callback: null
    /* etc. */
  })

  this._value = options.value
  this._flag = options.flag
  this._callback = options.callback
}

testFunction2({ value: 42 })

Get any option without errors via recursive Proxy

Contribution

Any contribution is appreciated. To get going, check out the contribution guidelines. Thank you and have fun!

License

ISC @ Richard King