JSPM

  • Created
  • Published
  • Downloads 6978
  • Score
    100M100P100Q125375F
  • License Apache-2.0

Wrap and validate optional values

Package Exports

  • stdopt
  • stdopt/base
  • stdopt/number
  • stdopt/opt
  • stdopt/string

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (stdopt) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

stdopt

Wrap and validate optional values

Usage

This package provides wrappers to check inputs and provide fallbacks. There is a general opt wrapper to check if a value is defined or not, as well as a handful of others for various primitives. The chained syntax is more verbose than the standard JS way (i.e. var str = opts.str || 'default'), but it is more solid and predictable.

var opt = require('stdopt/opt')
opt('some data').value() // => 'some data'
opt(null).or('other data').value() // => 'other data'
opt(null).or(undefined).value() // => throws error

// string primitive
var string = require('stdopt/string')
string('some text').value() // => 'some text'
string(true).or('other text').value() // => 'other text'
string(5).value() // => '5'

// number primitive
var number = require('stdopt/number')
number(5).value() // => 5
number(true).or(7).value() // => 7
number('11').value() // => 11

// boolean primitive
var boolean = require('stdopt/boolean')
boolean(false).value() // => false
boolean(null).or(true).value() // => true
boolean('True').value() // => true
boolean('fAlSe').value() // => false

// hash primitive
var hash = require('stdopt/hash')
hash({stuff: true}).value() // => {stuff: true}
hash(true).or({other: false}).value() // => {other: false}
hash([1, 2, 3]).value() // => throws error

// list primitive
var list = require('stdopt/list')
list([1, 2, 3]).value() // => [1, 2, 3]
list(true).or([4, 5, 6]).value() // => [4, 5, 6]
list({0: 'stuff', length: 1}).value() // => ['stuff']

## Custom

You can also create your own custom primitives,  by using the `Base` class and defining a custom static `parse` method.

```js
var Base = require('stdopt/base')

function lowercase (value) {
  if (!(this instanceof lowercase)) {
    return new lowercase(value)
  }
  Base.call(this, value)
}

lowercase.parse = function (value) {
  if (typeof value === 'string' && value.toLowerCase() === value) {
    return value.toLowerCase()
  }
}

lowercase('oh.').value() // => 'oh.'
lowercase('AHA!').or('oh.').value() // => 'oh.'
lowercase('AHA!').value() // => throws error

License

Apache-2.0