1.0.1 • Published 7 years ago
ensurelist v1.0.1
EnsureList
EnsureList enforces inputs to be arrays.
What's The Point?
When writing functional code in javascript, do you find yourself doing checks to ensure that everything is being passed as an array? Like this:
myObj = // some object or array
if (!Array.isArray(myObj)) {
myObj = [myObj]
}
The problems with this piece of code are: 1. It's additional code that obfuscates the implementation 2. It's repeated all over the application 3. It's inconsistent, or (worse) potentially wrong.
function myFn(someObj){
List(someObj).map(function(i){
return `Hello, ${i}`;
}).join("<br />");
}
myFn("World");
myFn(["World", "Universe"]);
myFn(null);
With this approach, we can handle all inputs the same way without any additional boilerplate.
Installation
npm install ensurelist
Usage
// Initialization
const List = require('ensurelist');
// Casting a string to an Array
let myList = List("hello world");
// myList == ["hello world"]
// Validating an Array
let myList = List([1,2,3])
// myList = [1,2,3]
// Null handling
let myList = List(null)
// myList = []