0.1.0 • Published 5 months ago

safe-dig v0.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

Safe Dig - JavaScript Utility for Safe Nested Access

safe-dig is a zero-dependency JavaScript utility that safely accesses deeply nested properties or indices in objects and arrays. It mimics Ruby's dig method but works for both objects and arrays in JavaScript, providing a robust solution for safely accessing nested data without throwing errors.

Features

  • Safe Access: Safely access deeply nested properties in objects or arrays without worrying about exceptions like TypeError or undefined.
  • Flexible: Works for both objects and arrays, allowing you to handle mixed structures.
  • Optional Prototype Method: Optionally add safeDig as a method to all JavaScript objects through the prototype, enabling seamless syntax like obj.safeDig(...).
  • Error Handling: Returns null if a property or index doesn't exist, preventing runtime errors.

Installation

To install the package via npm, run the following command:

npm install safe-dig

Or if you are using yarn:

yarn add safe-dig

Usage

Importing the Functions

You can use the safeDig function and the addSafeDigPrototype function independently.

const { safeDig, addSafeDigPrototype } = require('safe-dig');

1. Using safeDig

The safeDig function allows you to safely dig into an object or array and retrieve nested values without causing runtime errors.

Syntax:

safeDig(obj, ...keys);
  • obj: The object or array you want to access.
  • ...keys: The sequence of keys (for objects) or indices (for arrays) to access the desired value.

Example:

const obj = { a: [{ b: { c: 42 } }] };

// Access nested properties safely
console.log(safeDig(obj, 'a', 0, 'b', 'c')); // 42
console.log(safeDig(obj, 'a', 1, 'b', 'c')); // null (out of bounds)
console.log(safeDig(obj, 'x', 'y')); // null (key not found)

2. Using addSafeDigPrototype

If you want to add the safeDig method to all objects, you can use addSafeDigPrototype. This will allow you to call safeDig directly on any object, making your code more concise.

Syntax:

addSafeDigPrototype();

After calling this method, you can use safeDig on any object:

Example:

addSafeDigPrototype(); // Adds `safeDig` to all objects

const obj = { a: [{ b: { c: 42 } }] };

// Using `safeDig` directly on an object
console.log(obj.safeDig('a', 0, 'b', 'c')); // 42
console.log(obj.safeDig('a', 1, 'b', 'c')); // null (out of bounds)

3. TypeScript Support

safe-dig comes with full TypeScript support for autocompletion and type checking. When you install and use safe-dig in a TypeScript project, you'll get proper types for both the safeDig function and addSafeDigPrototype method.

TypeScript Example:

import { safeDig, addSafeDigPrototype } from 'safe-dig';

const obj = { a: [{ b: { c: 42 } }] };

// Safe access using safeDig function
console.log(safeDig(obj, 'a', 0, 'b', 'c')); // 42
console.log(safeDig(obj, 'a', 1, 'b', 'c')); // null (out of bounds)

// Apply the safeDig method to the prototype
addSafeDigPrototype();
console.log(obj.safeDig('a', 0, 'b', 'c')); // 42

API

safeDig<T>(obj: T, ...args: (string | number)[]): any

Safely digs through an object or array to access nested properties or indices.

  • obj: The object or array to dig into.
  • args: A sequence of keys (for objects) or indices (for arrays) to access the desired value.
  • Returns: The value found at the specified path, or null if not found.

addSafeDigPrototype(): void

Adds the safeDig method to the prototype of all objects in JavaScript. After calling this function, you can use obj.safeDig(...) directly on any object.

  • Returns: void

Example with Mixed Objects and Arrays

Here’s an example demonstrating how safeDig works for both objects and arrays:

const data = {
  users: [
    { name: 'Alice', profile: { age: 30, city: 'New York' } },
    { name: 'Bob', profile: { age: 25, city: 'Los Angeles' } },
  ],
};

// Safe access in objects and arrays
console.log(safeDig(data, 'users', 0, 'profile', 'age')); // 30
console.log(safeDig(data, 'users', 1, 'profile', 'city')); // 'Los Angeles'
console.log(safeDig(data, 'users', 2)); // null (index out of bounds)
console.log(safeDig(data, 'users', 0, 'profile', 'country')); // null (key not found)

Contributing

Feel free to contribute to safe-dig by submitting bug reports, suggestions, or pull requests. If you find any issues, please open an issue on GitHub.

Steps to Contribute

  1. Fork the repository.
  2. Clone your fork locally.
  3. Create a new branch for your changes.
  4. Make your changes and write tests if applicable.
  5. Push your changes to your fork.
  6. Create a pull request.

License

safe-dig is open-source software licensed under the MIT License.


Directory Structure

Here’s a brief overview of the project structure:

safe-dig/
├── LICENSE
├── README.md
├── package.json
├── index.js         # Main utility code
└── index.d.ts       # TypeScript declaration file

Final Thoughts

The safe-dig package provides a simple yet powerful way to safely access deeply nested values within objects and arrays in JavaScript. Whether you use it as a standalone function or apply it to all objects via the prototype, it ensures that your code is less prone to runtime errors.

Feel free to customize or extend this utility to meet your needs, and don’t forget to contribute back if you find any bugs or improvements!