npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

safe-variable-handler

v1.10.4

Published

A utility library for handling different types of variables safely.

Downloads

68

Readme

Safe Variable Handler

A utility library for handling different types of variables safely.

Have you ever encountered the frustrating "Uncaught TypeError: "".map is not a function" error while working with APIs? This often happens when the API response is expected to be an array, but due to various reasons, it turns out to be a non-array (e.g., an empty string).

This simple JavaScript library, Safe Variable Handler, is designed to tackle precisely this issue. It helps prevent common errors like "Uncaught TypeError" by safely checking if a variable is an array before performing operations like .map(). If the variable is not an array, the library provides a fallback, preventing your code from breaking.

Uncaught ReferenceError: global is not defined in case of error with vite, please see this discussion: https://github.com/vitejs/vite/discussions/5912

in case of error: TS1192: Module '"/node_modules/safe-variable-handler/safe"' has no default export resolve with: import * as safe from 'safe-variable-handler'

Installation

npm install safe-variable-handler
yarn add safe-variable-handler

Usage

// Import the library
// import * as safe from 'safe-variable-handler'

const safe = require('safe-variable-handler');

// Example 1: Safely executing a callback function
const executeCallback = (callback) => {
  const safeCallback = safe.func(callback);

  // Safely execute the callback or provide a default behavior
  return safeCallback() ?? 'default behavior'
};

// Example 2: Safely processing an array of numbers
const processNumbers = (data) => {
  const safeNumbersArray = safe.array(data);

  // Safely calculate the sum of numbers or provide a default value
  const sum = safeNumbersArray.reduce((acc, num) => acc + num, 0);
  console.log('Sum of numbers:', sum);
};

// Example 3: Safely accessing properties in a nested object
const accessNestedProperties = (apiResponse) => {
  const safeResponseObject = safe.object(apiResponse);

  // Safely access nested properties or provide default values
  const username = safeResponseObject.user?.name || 'Guest';
  const email = safeResponseObject.user?.email || '[email protected]';

  console.log('Username:', username);
  console.log('Email:', email);
};

// You can now confidently use these functions without worrying about unexpected input types causing errors.

safe.func(() => console.log("test"))();
safe.func(null)();

console.log(safe.array("").map((item) => item));
console.log(safe.array([1, 2, 3]).map((item) => item));

console.log(Object.keys(safe.object(null)));
console.log(Object.keys(safe.object({ key: 1 })));

Functions

array(variable)

Safely returns an array. If the input is not an array, an empty array is returned.

object(variable)

Safely returns an object. If the input is not an object, an empty object is returned.

func(variable)

Safely returns a function. If the input is not a function, a dummy function is returned.

Global Debugging

To enable debug warnings, set the global variable DEBUG before using the library.

Example:

// Enable debug mode
global.DEBUG = true;

// Now use the library
const safe = require('safe-variable-handler')
safe.array('not an array').map(item => item);
// Debug warning will be printed Variable is not an array. Type: string