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

util-array-object-or-both

Package Overview
Dependencies
Maintainers
1
Versions
152
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

util-array-object-or-both

Validate and normalise user choice: array, object or both?

  • 1.2.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
394
increased by60.16%
Maintainers
1
Weekly downloads
 
Created
Source

util-array-object-or-both

Validate and normalise user choice: array, object or both?

Link to npm page Build Status bitHound Overall Score bitHound Dependencies bitHound Dev Dependencies Coverage Status Known Vulnerabilities Downloads/Month View dependencies as 2D chart Test in browser

Table of Contents

Install

$ npm install util-array-object-or-both

The source is in ES6, but transpiled code (ES5) is served.

Purpose

When I give the user ability to choose their preference out of: array, object or any, I want to:

  • Allow users to input the preference in many ways: for example, for array, I also want to accept: Arrays, add, ARR, a. Similar thing goes for options object and any.
  • Normalise the choice - recognise it and set it to one of the three following strings: array, object or any. This is necessary because we want set values to use in our programs. You can't have five values for array in an IF statement, for example.
  • When a user sets the preference to unrecognised string, I want to throw a meaningful error message. Technically this will be achieved using an options object.
  • Enforce lowercase and trim and input, to maximise the input possibilities

Assumed to be an array-typeobject-typeeither type
Input string:arrayobjectany

arraysobjectsall

arrobjeverything

arayobboth

arroeither

aeach

whatever

e

------------
Output string:arrayobjectany

API

API is simple - just pass your value through this library's function. If it's valid, it will be normalised to either array or object or any. If it's not valid, an error will be thrown.

Input argumentTypeObligatory?Description
inputStringyesLet users choose from variations of "array", "object" or "both". See above.
optsPlain objectnoOptional Options Object. See below for its API.

Options object lets you customise the thrown error message. It's format is the following:

${opts.msg}The ${opts.optsVarName} was customised to an unrecognised value: ${str}. Please check it against the API documentation.
options object's keyTypeObligatory?DefaultDescription
{
msgStringno``Append the message in front of the thrown error.
optsVarNameStringnogiven variableThe name of the variable we are checking here.
}

For example, set optsVarName to opts.only and set msg to posthtml-ast-delete-key/deleteKey(): [THROW_ID_01] and the error message thrown if user misconfigures the setting will be, for example:

posthtml-ast-delete-key/deleteKey(): [THROW_ID_01] The variable "opts.only" was customised to an unrecognised value: sweetcarrots. Please check it against the API documentation.

Use

// require this library:
const arrayOrObjectOrBoth = require('util-array-object-or-both')
// and friends:
const clone = require('lodash.clonedeep')
const checkTypes = require('check-types-mini')
const objectAssign = require('object-assign')
// let's say you have a function:
function myPrecious (input, opts) {
  // now you want to check your options object, is it still valid after users have laid their sticky paws on it:
  // define defaults:
  let defaults = {
    lalala: null,
    only: 'object' // <<< this is the value we're particularly keen to validate, is it `array`|`object`|`any`
  }
  // clone the defaults to safeguard it, and then, object-assign onto defaults.
  // basically you fill missing values with default-ones
  opts = objectAssign(clone(defaults), opts)
  // now, use "check-types-mini" to validate the types:
  checkTypes(opts, defaults,
    {
      // give a meaningful message in case it throws,
      // customise the library `check-types-mini`:
      msg: 'my-library/myPrecious(): [THROW_ID_01]',
      optsVarName: 'opts',
      schema: {
        lalala: ['null', 'string'],
        only: ['null', 'string']
      }
    }
  )
  // by this point, we can guarantee that opts.only is either `null` or `string`.
  // if it's a `string`, let's validate is its values among accepted-ones:
  opts.only = arrayOrObjectOrBoth(opts.only, {
    msg: 'my-library/myPrecious(): [THROW_ID_02]',
    optsVarName: 'opts.only'
  })
  // now we can guarantee that it's either falsey (undefined or null) OR:
  //   - `object`
  //   - `array`
  //   - `any`

  // now you can use `opts.only` in your function safely.
  ...
  // rest of the function...
}

Critique

You may ask, why on Earth you would need a package for such thing? It's not very universal to be useful for society, is it?

Actually, it is.

I discovered that when working with AST's, you often need to tell your tools to process (traverse, delete, and so on) EITHER objects OR arrays or both. That's where this library comes in: standardise the choice out of three options and give a user a wide amount of values to use.

I think the API should accept a very wide spectrum of values, so users would not even need to check the API documentation - they'd just describe what they want, in plain English.

I'm going to use it in:

and others. So, it's not that niche as it might seem!

Testing

$ npm test

Unit tests use AVA, linting is done via ESLint on airbnb-base preset. I aim to have 100% unit test coverage (per-line, function and branch).

Contributing

If you see anything incorrect whatsoever, do raise an issue. If you file a pull request, I'll do my best to merge it quickly. If you have any comments on the code, including ideas how to improve something, don't hesitate to contact me by email.

If something doesn't work as you wished or you don't understand the inner working of this library, do raise an issue. I'm happy to explain what's happening. Often some part of my README documentation is woolly, and I can't spot it myself. I need user feedback.

Also, if you miss a feature, request it by raising an issue as well.

I know it never happens but if you would ever forked it and worked on a new feature, before filing a pull request, please make sure code is following the rules set in .eslintrc and npm run test passes fine. It's basically an airbnb-base rules preset of eslint with few exceptions: 1. No semicolons. 2. Allow plus-plus in for loops. See ./eslintrc.

I dropped JS Standard because it misses many useful ESLint rules and has been neglected by its maintainers, using half-year-old version of ESLint.

Cheers!

Licence

MIT License (MIT)

Copyright (c) 2017 Codsen Ltd, Roy Revelt

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Keywords

FAQs

Package last updated on 22 Sep 2017

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc