CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-xe-utils

Comprehensive JavaScript utility library with 150+ functions for objects, arrays, dates, strings, numbers, and more

Overview
Eval results
Files

function-utilities.mddocs/

Function Utilities

Function manipulation utilities including binding, throttling, debouncing, and execution control. Perfect for event handling, performance optimization, and creating specialized function behaviors in modern web applications.

Capabilities

Function Binding

Utilities for binding functions to specific contexts and pre-applying arguments.

/**
 * Bind function to specific context with optional pre-applied arguments
 * @param fn - Function to bind
 * @param thisArg - Context to bind function to
 * @param args - Arguments to pre-apply
 * @returns Bound function
 */
function bind(fn: Function, thisArg: any, ...args: any[]): Function;

Property Access Functions

Create functions for accessing object properties.

/**
 * Create property accessor function
 * @param path - Property path (string or array)
 * @returns Function that accesses the specified property
 */
function property(path: string | string[]): (obj: any) => any;

Execution Control

Control when and how many times functions execute.

/**
 * Create function that only executes once
 * @param fn - Function to execute once
 * @returns Function that executes only on first call
 */
function once<T extends (...args: any[]) => any>(fn: T): T;

/**
 * Create function that executes only after being called n times
 * @param count - Number of calls required before execution
 * @param fn - Function to execute after count calls
 * @returns Function that tracks call count
 */
function after(count: number, fn: Function): Function;

/**
 * Create function that executes only before being called n times
 * @param count - Maximum number of executions
 * @param fn - Function to execute before count reached
 * @returns Function that stops executing after count
 */
function before(count: number, fn: Function): Function;

Performance Control

Throttling and debouncing functions for performance optimization.

/**
 * Throttle function execution to at most once per wait period
 * @param fn - Function to throttle
 * @param wait - Wait time in milliseconds
 * @param options - Throttling options
 * @returns Throttled function with cancel method
 */
function throttle<T extends (...args: any[]) => any>(
  fn: T, 
  wait: number, 
  options?: ThrottleOptions
): T & { cancel(): void };

interface ThrottleOptions {
  /** Execute on leading edge (default: true) */
  leading?: boolean;
  /** Execute on trailing edge (default: true) */
  trailing?: boolean;
}

/**
 * Debounce function execution to occur only after wait period of inactivity
 * @param fn - Function to debounce
 * @param wait - Wait time in milliseconds
 * @param options - Debouncing options
 * @returns Debounced function with cancel method
 */
function debounce<T extends (...args: any[]) => any>(
  fn: T, 
  wait: number, 
  options?: DebounceOptions
): T & { cancel(): void };

interface DebounceOptions {
  /** Execute on leading edge (default: false) */
  leading?: boolean;
  /** Execute on trailing edge (default: true) */
  trailing?: boolean;
}

Delayed Execution

Utilities for delaying function execution.

/**
 * Execute function after specified delay
 * @param fn - Function to execute
 * @param wait - Delay in milliseconds
 * @param args - Arguments to pass to function
 * @returns Timeout ID for cancellation
 */
function delay(fn: Function, wait: number, ...args: any[]): number;

Utility Functions

Basic utility functions for common patterns.

/**
 * No-operation function (does nothing)
 * @returns undefined
 */
function noop(): void;

Usage Examples:

import { 
  bind, property, once, after, before, throttle, debounce, delay, noop 
} from 'xe-utils';

// Function binding
const obj = {
  name: 'Alice',
  greet(message) {
    return `${message}, ${this.name}!`;
  }
};

const boundGreet = bind(obj.greet, obj);
console.log(boundGreet('Hello')); // 'Hello, Alice!'

// Pre-applying arguments
const add = (a, b, c) => a + b + c;
const addFive = bind(add, null, 5);
console.log(addFive(10, 15)); // 30 (5 + 10 + 15)

// Property accessor functions
const users = [
  { name: 'Alice', profile: { age: 25 } },
  { name: 'Bob', profile: { age: 30 } }
];

const getName = property('name');
const getAge = property(['profile', 'age']);

console.log(users.map(getName)); // ['Alice', 'Bob']
console.log(users.map(getAge)); // [25, 30]

// Execute once
let initCount = 0;
const initialize = once(() => {
  initCount++;
  console.log('Initializing application...');
  return 'initialized';
});

console.log(initialize()); // 'Initializing application...' + 'initialized'
console.log(initialize()); // 'initialized' (no console output)
console.log(initCount); // 1

// Execute after N calls
let setupComplete = false;
const completeSetup = after(3, () => {
  setupComplete = true;
  console.log('Setup completed after 3 steps!');
});

completeSetup(); // Nothing happens
completeSetup(); // Nothing happens  
completeSetup(); // 'Setup completed after 3 steps!'

// Execute before N calls
const limitedFunction = before(3, (msg) => {
  console.log(`Message: ${msg}`);
});

limitedFunction('First'); // 'Message: First'
limitedFunction('Second'); // 'Message: Second'
limitedFunction('Third'); // Nothing happens
limitedFunction('Fourth'); // Nothing happens

// Throttling (limit execution frequency)
const expensiveOperation = () => {
  console.log('Expensive operation executed at', new Date().toISOString());
};

const throttledOperation = throttle(expensiveOperation, 1000);

// Rapid calls - only executes at most once per second
throttledOperation(); // Executes immediately
throttledOperation(); // Ignored
throttledOperation(); // Ignored
setTimeout(throttledOperation, 1100); // Executes after 1 second

// Debouncing (delay execution until activity stops)
const searchAPI = (query) => {
  console.log('Searching for:', query);
  // API call here
};

const debouncedSearch = debounce(searchAPI, 300);

// Typing simulation - only searches after user stops typing
debouncedSearch('h'); // Cancelled
debouncedSearch('he'); // Cancelled
debouncedSearch('hel'); // Cancelled
debouncedSearch('hello'); // Executes after 300ms of inactivity

// Event handler examples
function setupEventHandlers() {
  const button = document.getElementById('save-button');
  const searchInput = document.getElementById('search-input');
  const scrollHandler = throttle(() => {
    console.log('Scroll position:', window.scrollY);
  }, 100);
  
  const searchHandler = debounce((event) => {
    searchAPI(event.target.value);
  }, 300);
  
  // Prevent double-clicks on save button
  const saveHandler = once(() => {
    console.log('Saving data...');
    // Save logic here
  });
  
  window.addEventListener('scroll', scrollHandler);
  searchInput.addEventListener('input', searchHandler);
  button.addEventListener('click', saveHandler);
}

// Delayed execution
console.log('Starting delayed operations...');

delay(() => {
  console.log('This runs after 1 second');
}, 1000);

delay((name, age) => {
  console.log(`User: ${name}, Age: ${age}`);
}, 2000, 'Alice', 25);

// Practical throttle/debounce patterns
class ResizeHandler {
  constructor() {
    this.handleResize = throttle(this.onResize.bind(this), 200);
    window.addEventListener('resize', this.handleResize);
  }
  
  onResize() {
    console.log('Window resized to:', window.innerWidth, 'x', window.innerHeight);
    // Update layout logic here
  }
  
  destroy() {
    window.removeEventListener('resize', this.handleResize);
    this.handleResize.cancel(); // Cancel pending executions
  }
}

class SearchComponent {
  constructor() {
    this.search = debounce(this.performSearch.bind(this), 300);
  }
  
  onInput(query) {
    if (query.length > 2) {
      this.search(query);
    } else {
      this.search.cancel(); // Cancel pending search
    }
  }
  
  async performSearch(query) {
    console.log('Searching for:', query);
    // API call implementation
  }
}

// No-op function for callbacks
const optionalCallback = noop; // Safe default callback
someAsyncFunction(data, optionalCallback);

Install with Tessl CLI

npx tessl i tessl/npm-xe-utils

docs

array-operations.md

base-utilities.md

date-time.md

function-utilities.md

index.md

number-operations.md

object-operations.md

string-processing.md

type-checking.md

web-browser.md

tile.json