New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

stdopt

Package Overview
Dependencies
Maintainers
1
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

stdopt

Wrap and validate optional values

10.2.1
Source
npm
Version published
Weekly downloads
4.4K
-22.44%
Maintainers
1
Weekly downloads
 
Created
Source

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('one').value() // => ['one']
list(null).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.

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

Keywords

options

FAQs

Package last updated on 17 Apr 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts