CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-utility

A collection of useful TypeScript/JavaScript utilities for crypto, date, string, number, JSON operations and more.

Pending
Overview
Eval results
Files

optimize.mddocs/

Optimization Utilities

Performance optimization utilities including try-catch wrappers, safe property access, and efficient argument handling designed to improve application performance and reduce errors.

Capabilities

Try-Catch Wrapper

Optimized try-catch wrapper that returns structured results instead of throwing exceptions.

/**
 * Optimize try-catch operations with structured return
 * @param fn - Function to execute safely
 * @returns Object with error and value properties
 */
function tryCatch<T = any>(fn: () => T): {error: Error | undefined, value: T | undefined};

Usage Examples:

import { tryCatch } from "utility";

// Safe JSON parsing
const jsonResult = tryCatch(() => JSON.parse('{"valid": "json"}'));
if (jsonResult.error) {
  console.error('JSON parse failed:', jsonResult.error.message);
} else {
  console.log('Parsed data:', jsonResult.value);
}

// Safe function execution
const mathResult = tryCatch(() => {
  const result = someComplexCalculation();
  return result * 2;
});

// Safe property access
const propResult = tryCatch(() => obj.deeply.nested.property);
if (propResult.value !== undefined) {
  console.log('Property exists:', propResult.value);
}

// Safe API call
const apiResult = tryCatch(() => syncApiCall());
if (apiResult.error) {
  handleApiError(apiResult.error);
} else {
  processApiResponse(apiResult.value);
}

Unstable Methods Object

Object containing experimental methods that may change in future versions. Required for TypeScript compatibility when using certain method names as keywords.

/**
 * Object containing unstable/experimental methods for TypeScript compatibility
 * WARNING: Methods in this object may change or be removed in future versions
 */
const UNSTABLE_METHOD: {
  try: typeof tryCatch;
};

Usage Examples:

import { UNSTABLE_METHOD } from "utility";

// Required in TypeScript when 'try' conflicts with keyword
const result = UNSTABLE_METHOD.try(() => riskyOperation());

// Identical functionality to direct tryCatch import
import { tryCatch } from "utility";
const sameResult = tryCatch(() => riskyOperation());

// Dynamic method access (advanced usage)
const methodName = 'try' as keyof typeof UNSTABLE_METHOD;
const safeResult = UNSTABLE_METHOD[methodName](() => someFunction());

// Use case: When building wrapper libraries
class SafeExecutor {
  static execute<T>(fn: () => T) {
    // Use UNSTABLE_METHOD when 'try' method name is needed
    return UNSTABLE_METHOD.try(fn);
  }
}

Important Notes:

  • Use direct tryCatch import when possible for better stability
  • UNSTABLE_METHOD.try is functionally identical to tryCatch
  • This object exists primarily for TypeScript keyword compatibility
  • Methods in UNSTABLE_METHOD may be deprecated in future versions

Safe Property Access

Safely access nested object properties without throwing errors.

/**
 * Safely access nested object properties (avoid if (a && a.b && a.b.c))
 * @param obj - Root object
 * @param keys - Property path as separate arguments
 * @returns Property value or undefined if path doesn't exist
 */
function dig(obj?: any, ...keys: string[]): any;

Usage Examples:

import { dig } from "utility";

// Safe nested property access
const user = {
  profile: {
    address: {
      street: '123 Main St',
      city: 'Portland'
    }
  }
};

const street = dig(user, 'profile', 'address', 'street');
// Result: '123 Main St'

const nonexistent = dig(user, 'profile', 'phone', 'number');
// Result: undefined (no error thrown)

// Handle null/undefined objects
const nullResult = dig(null, 'any', 'path');
// Result: undefined

const undefinedResult = dig(undefined, 'any', 'path');
// Result: undefined

// Empty keys returns the object
const sameObject = dig(user);
// Result: user object

// API response handling
const apiResponse = {
  data: {
    users: [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' }
    ]
  }
};

const firstUserName = dig(apiResponse, 'data', 'users', '0', 'name');
// Result: 'Alice'

const missingData = dig(apiResponse, 'data', 'posts', '0', 'title');
// Result: undefined (safe access to non-existent path)

Arguments to Array Conversion

Optimized conversion of arguments-like objects to arrays.

/**
 * Optimize arguments to array conversion
 * @param args - Array-like arguments object
 * @returns Proper array with same elements
 */
function argumentsToArray(args: any[]): any[];

Usage Examples:

import { argumentsToArray } from "utility";

// Convert function arguments
function variableArgs() {
  const argsArray = argumentsToArray(arguments as any);
  return argsArray.map(arg => arg.toString());
}

// Usage in modern functions (though rest parameters are preferred)
function legacyFunction() {
  const args = argumentsToArray(arguments as any);
  args.forEach((arg, index) => {
    console.log(`Argument ${index}:`, arg);
  });
}

// Array-like object conversion
function processArrayLike(arrayLike: any) {
  const realArray = argumentsToArray(arrayLike);
  return realArray.filter(item => item != null);
}

// Performance-critical argument handling
function highPerformanceFunction() {
  // Faster than Array.from(arguments) or [...arguments] in some engines
  const args = argumentsToArray(arguments as any);
  return args.reduce((sum, num) => sum + num, 0);
}

// NodeList conversion (DOM)
function convertNodeList(nodeList: NodeListOf<Element>) {
  const elements = argumentsToArray(Array.from(nodeList));
  return elements.map(el => el.tagName);
}

Install with Tessl CLI

npx tessl i tessl/npm-utility

docs

array.md

crypto.md

date.md

fs.md

function.md

index.md

json.md

number.md

object.md

optimize.md

string.md

timeout.md

web.md

tile.json