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?

  • 2.2.0
  • 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?

Minimum Node version required Repository is on BitBucket Coverage View dependencies as 2D chart Downloads/Month Test in browser Code style: prettier MIT License

Table of Contents

Install

npm i util-array-object-or-both
// consume via a CommonJS require:
const arrObjOrBoth = require("util-array-object-or-both");
// or as an ES Module:
import arrObjOrBoth from "util-array-object-or-both";

Here's what you'll get:

TypeKey in package.jsonPathSize
Main export - CommonJS version, transpiled to ES5, contains require and module.exportsmaindist/util-array-object-or-both.cjs.js3 KB
ES module build that Webpack/Rollup understands. Untranspiled ES6 code with import/export.moduledist/util-array-object-or-both.esm.js2 KB
UMD build for browsers, transpiled, minified, containing iife's and has all dependencies baked-inbrowserdist/util-array-object-or-both.umd.js17 KB

⬆ back to top

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

⬆ back to top

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 ast-delete-key/deleteKey(): [THROW_ID_01] and the error message thrown if user misconfigures the setting will be, for example:

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.

⬆ back to top

Use

// require this library:
const arrObjOrBoth = 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 = arrObjOrBoth(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...
}

⬆ back to top

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 (from three options) and relieve the user from the need to remember the exact value.

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!

⬆ back to top

Contributing

  • If you want a new feature in this package or you would like us to change some of its functionality, raise an issue on this repo.

  • If you tried to use this library but it misbehaves, or you need advice setting it up, and its readme doesn't make sense, just document it and raise an issue on this repo.

  • If you would like to add or change some features, just fork it, hack away, and file a pull request. We'll do our best to merge it quickly. Prettier is enabled, so you don't need to worry about the code style.

⬆ back to top

Licence

MIT License (MIT)

Copyright © 2018 Codsen Ltd, Roy Revelt

Keywords

FAQs

Package last updated on 16 Jun 2018

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