Socket
Socket
Sign inDemoInstall

ensure-array

Package Overview
Dependencies
0
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    ensure-array

Ensure that an object is an array. Moves error checking out of your code.


Version published
Weekly downloads
32K
increased by5.38%
Maintainers
1
Install size
7.29 kB
Created
Weekly downloads
 

Readme

Source

ensure-array

Simple convenience function which ensures that you are dealing with an array and you can eliminate noise from your code.

For Example:

  var array = require('ensure-array');
  
  function foo(bar) {
    array(bar).forEach(function (x) {
      //do something with each item
    });
  }

Instead of doing something like this:

  function foo(bar) {
    if (bar === undefined) return;
    if (bar === null) return;
    if (!Array.isArray(bar)) bar = [bar];
    bar.forEach(function (x) {
      //do something with each item
    });
  }

Description

It gets rid of the noise and coerces what is provided into an array, so you do not have to litter your code with a bunch of extraneous checks.

Here is the logic behind the function:

  1. if nothing passed to the function return empty array []
  2. if single argument passed is undefined or null return empty array []
  3. if single argument passed is already an array, return it unchanged
  4. otherwise return array containing all of the arguments

Here is the actual code which makes it happen

module.exports = function array(a, b, n) {
 if (arguments.length === 0) return [];            //no args, ret []
 if (arguments.length === 1) {                     //single argument
   if (a === undefined || a === null) return [];   //  undefined or null, ret []
   if (Array.isArray(a)) return a;                 //  isArray, return it
 }
 return Array.prototype.slice.call(arguments);     //return array with copy of all arguments
};

Installation

  npm install ensure-array

Usage

  var array = require('ensure-array');  // get handle to the function
  var foo = array(whatever);               // foo will now safely be an array

Status

  • 2011-12-08 - 0.0.4 - Update tapr / tap versions
  • 2011-12-01 - 0.0.3 - Updated to support any version of Node.js

License

  • MIT license

Contributors

  • Author: Jeff Barczewski (@jeffbski)

Contributing

FAQs

Last updated on 24 Mar 2012

Did you know?

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc