or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

ajax.mdanimations.mdcss-styling.mddata-storage.mddom-manipulation.mddom-traversal.mdevents.mdforms.mdindex.mdutilities.md
tile.json

utilities.mddocs/

Utilities and Core Functions

Essential utility functions for object manipulation, type checking, iteration, and cross-browser compatibility. jQuery provides a comprehensive set of utilities that extend JavaScript's built-in capabilities.

Capabilities

Object Utilities

Deep and shallow object merging with recursive copying and property extension.

/**
 * Merge contents of objects into target object
 * @param target - Target object to extend
 * @param sources - Source objects to merge from
 * @returns Extended target object
 */
$.extend(target: object, ...sources: object[]): object;

/**
 * Deep merge contents of objects into target object
 * @param deep - Boolean flag for deep copying
 * @param target - Target object to extend
 * @param sources - Source objects to merge from
 * @returns Extended target object
 */
$.extend(deep: boolean, target: object, ...sources: object[]): object;

Usage Examples:

// Shallow merge
const defaults = { color: 'blue', size: 'medium' };
const options = { size: 'large', weight: 'bold' };
const settings = $.extend({}, defaults, options);
// Result: { color: 'blue', size: 'large', weight: 'bold' }

// Deep merge
const defaultConfig = {
  ui: { theme: 'light', animations: true },
  api: { timeout: 5000, retries: 3 }
};
const userConfig = {
  ui: { theme: 'dark' },
  api: { timeout: 10000 }
};
const config = $.extend(true, {}, defaultConfig, userConfig);
// Result: {
//   ui: { theme: 'dark', animations: true },
//   api: { timeout: 10000, retries: 3 }
// }

// Extend jQuery itself
$.extend({
  customUtility: function(value) {
    return value * 2;
  }
});
// Now $.customUtility() is available

// Extend jQuery prototype
$.fn.extend({
  customMethod: function() {
    return this.addClass('custom');
  }
});
// Now $('.selector').customMethod() is available

Iteration Utilities

Iterate over arrays, objects, and array-like structures with early termination support.

/**
 * Generic iterator for objects and arrays
 * @param collection - Array or object to iterate over
 * @param callback - Function called for each item (index, value)
 * @returns Original collection for chaining
 */
$.each(collection: any[] | object, callback: function(index: number | string, value: any): any): any[] | object;

/**
 * Transform array or object elements using callback function
 * @param collection - Array or object to transform
 * @param callback - Function to transform each element (value, index)
 * @returns New array containing transformed values
 */
$.map(collection: any[] | object, callback: function(value: any, index: number | string): any): any[];

/**
 * Filter array elements using callback function
 * @param array - Array to filter
 * @param callback - Filter function (element, index)
 * @param invert - Invert filter results
 * @returns Filtered array
 */
$.grep(array: any[], callback: function(element: any, index: number): boolean, invert?: boolean): any[];

Usage Examples:

// Iterate over array
$.each(['apple', 'banana', 'cherry'], function(index, value) {
  console.log(index + ': ' + value);
});
// Output: 0: apple, 1: banana, 2: cherry

// Iterate over object
$.each({ name: 'John', age: 30, city: 'Boston' }, function(key, value) {
  console.log(key + ': ' + value);
});
// Output: name: John, age: 30, city: Boston

// Early termination
$.each([1, 2, 3, 4, 5], function(index, value) {
  if (value === 3) {
    return false; // Break out of loop
  }
  console.log(value);
});
// Output: 1, 2

// Transform array
const doubled = $.map([1, 2, 3, 4], function(value) {
  return value * 2;
});
// Result: [2, 4, 6, 8]

// Transform object
const values = $.map({ a: 1, b: 2, c: 3 }, function(value, key) {
  return value * 10;
});
// Result: [10, 20, 30]

// Filter array
const evenNumbers = $.grep([1, 2, 3, 4, 5, 6], function(n) {
  return n % 2 === 0;
});
// Result: [2, 4, 6]

// Inverted filter
const oddNumbers = $.grep([1, 2, 3, 4, 5, 6], function(n) {
  return n % 2 === 0;
}, true);
// Result: [1, 3, 5]

Type Checking

Determine types of values with cross-browser compatibility and jQuery-specific extensions.

/**
 * Determine detailed type of value
 * @param obj - Value to check type of
 * @returns Type string (e.g., 'string', 'number', 'array', 'date', etc.)
 */
$.type(obj: any): string;

/**
 * Test if value is a plain JavaScript object
 * @param obj - Value to test
 * @returns true if plain object, false otherwise
 */
$.isPlainObject(obj: any): boolean;

/**
 * Test if object has no enumerable properties
 * @param obj - Object to test
 * @returns true if empty, false otherwise
 */
$.isEmptyObject(obj: any): boolean;

/**
 * Test if value is a function (deprecated - use typeof)
 * @param obj - Value to test
 * @returns true if function, false otherwise
 */
$.isFunction(obj: any): boolean;

/**
 * Test if value is an array (deprecated - use Array.isArray)
 * @param obj - Value to test
 * @returns true if array, false otherwise
 */
$.isArray(obj: any): boolean;

/**
 * Test if value is numeric
 * @param obj - Value to test
 * @returns true if numeric, false otherwise
 */
$.isNumeric(obj: any): boolean;

Usage Examples:

// Detailed type checking
$.type(null);          // 'null'
$.type(undefined);     // 'undefined'
$.type(true);          // 'boolean'
$.type(42);            // 'number'
$.type('hello');       // 'string'
$.type([]);            // 'array'
$.type({});            // 'object'
$.type(new Date());    // 'date'
$.type(/regex/);       // 'regexp'
$.type(function() {}); // 'function'

// Plain object testing
$.isPlainObject({});              // true
$.isPlainObject({ a: 1 });        // true
$.isPlainObject(new Object());    // true
$.isPlainObject([]);              // false
$.isPlainObject(new Date());      // false
$.isPlainObject(null);            // false

// Empty object testing
$.isEmptyObject({});              // true
$.isEmptyObject({ a: 1 });        // false
$.isEmptyObject([]);              // true (array has no enumerable properties)

// Numeric testing
$.isNumeric(42);                  // true
$.isNumeric('42');                // true
$.isNumeric('42.5');              // true
$.isNumeric('42px');              // false
$.isNumeric('hello');             // false
$.isNumeric(NaN);                 // false
$.isNumeric(Infinity);            // false

// Type-based processing
function processValue(value) {
  switch ($.type(value)) {
    case 'string':
      return value.toUpperCase();
    case 'number':
      return value * 2;
    case 'array':
      return value.length;
    case 'object':
      return Object.keys(value).length;
    default:
      return value;
  }
}

Array Utilities

Convert array-like objects to arrays and perform array operations.

/**
 * Convert array-like object to true JavaScript array
 * @param arrayLike - Array-like object to convert
 * @param results - Optional existing array to merge into
 * @returns JavaScript array
 */
$.makeArray(arrayLike: any, results?: any[]): any[];

/**
 * Search for value in array and return index
 * @param value - Value to search for
 * @param array - Array to search in
 * @param fromIndex - Optional starting index
 * @returns Index of value or -1 if not found
 */
$.inArray(value: any, array: any[], fromIndex?: number): number;

/**
 * Merge contents of second array into first array
 * @param first - First array (modified in place)
 * @param second - Second array to merge from
 * @returns First array with merged contents
 */
$.merge(first: any[], second: any[]): any[];

/**
 * Remove duplicate elements from array and sort by document order
 * @param array - Array to process
 * @returns Array with duplicates removed
 */
$.unique(array: any[]): any[];

Usage Examples:

// Convert NodeList to array
const divs = $.makeArray(document.getElementsByTagName('div'));
console.log(Array.isArray(divs)); // true

// Convert arguments object to array
function myFunction() {
  const argsArray = $.makeArray(arguments);
  return argsArray.join(', ');
}

// Search in array
const fruits = ['apple', 'banana', 'cherry'];
$.inArray('banana', fruits);        // 1
$.inArray('orange', fruits);        // -1
$.inArray('cherry', fruits, 2);     // 2 (start search from index 2)

// Merge arrays
const array1 = ['a', 'b'];
const array2 = ['c', 'd'];
$.merge(array1, array2);
console.log(array1); // ['a', 'b', 'c', 'd']

// Remove duplicates
const duplicated = [1, 2, 2, 3, 1, 4];
const unique = $.unique(duplicated.slice()); // slice() to avoid modifying original
console.log(unique); // [1, 2, 3, 4]

// Convert jQuery object to array
const elements = $('.item').toArray(); // Same as $.makeArray($('.item'))

String Utilities

String manipulation and formatting utilities.

/**
 * Trim whitespace from beginning and end of string (deprecated - use String.prototype.trim)
 * @param str - String to trim
 * @returns Trimmed string
 */
$.trim(str: string): string;

/**
 * Convert kebab-case or snake_case to camelCase
 * @param str - String to convert
 * @returns camelCase string
 */
$.camelCase(str: string): string;

Usage Examples:

// Trim whitespace (use native trim() instead)
$.trim('  hello world  '); // 'hello world'

// Convert to camelCase
$.camelCase('background-color');    // 'backgroundColor'
$.camelCase('border-top-width');    // 'borderTopWidth'
$.camelCase('data-user-name');      // 'dataUserName'
$.camelCase('some_snake_case');     // 'someSnakeCase'

// Useful for CSS property conversion
const cssProperty = 'margin-left';
const jsProperty = $.camelCase(cssProperty);
element.style[jsProperty] = '10px';

Miscellaneous Utilities

Additional utility functions for common tasks.

/**
 * Empty function for use as default callback
 * @returns undefined
 */
$.noop(): void;

/**
 * Throw error with message
 * @param message - Error message
 * @throws Error with specified message
 */
$.error(message: string): never;

/**
 * Execute JavaScript code in global scope
 * @param code - JavaScript code to execute
 * @param options - Optional execution options
 * @param doc - Optional document context
 */
$.globalEval(code: string, options?: object, doc?: Document): void;

/**
 * Current timestamp (deprecated - use Date.now())
 * @returns Current timestamp in milliseconds
 */
$.now(): number;

/**
 * Unique identifier for this jQuery instance
 */
$.expando: string;

/**
 * Global counter for generating unique IDs
 */
$.guid: number;

Usage Examples:

// Default callback
function setupCallback(callback) {
  callback = callback || $.noop;
  // callback is now safe to call
  callback();
}

// Error throwing
function validateInput(input) {
  if (!input) {
    $.error('Input is required');
  }
}

// Global code execution
$.globalEval('var globalVar = "Hello World";');
console.log(window.globalVar); // 'Hello World'

// Execute code with nonce for CSP
$.globalEval('console.log("Secure execution");', {
  nonce: 'abc123'
});

// Unique identifiers
const uniqueId = 'element_' + $.guid++;
console.log($.expando); // jQuery unique string for data storage

// Timestamp (use Date.now() instead)
const timestamp = $.now();

Deferred and Promise Utilities

Create and manage asynchronous operations with jQuery's Deferred system.

/**
 * Create deferred object for managing asynchronous operations
 * @param beforeStart - Optional function called before deferred is created
 * @returns Deferred object
 */
$.Deferred(beforeStart?: function): JQueryDeferred;

/**
 * Create resolved or aggregate promise from multiple deferreds
 * @param deferreds - Deferred objects or promises to aggregate
 * @returns Promise that resolves when all inputs resolve
 */
$.when(...deferreds: any[]): JQueryPromise;

Usage Examples:

// Create custom deferred
function asyncOperation() {
  const deferred = $.Deferred();
  
  setTimeout(function() {
    if (Math.random() > 0.5) {
      deferred.resolve('Operation succeeded');
    } else {
      deferred.reject('Operation failed');
    }
  }, 1000);
  
  return deferred.promise();
}

// Use custom deferred
asyncOperation().done(function(result) {
  console.log('Success:', result);
}).fail(function(error) {
  console.log('Error:', error);
});

// Aggregate multiple promises
$.when(
  $.get('/api/user'),
  $.get('/api/posts'),
  $.get('/api/comments')
).done(function(userData, postsData, commentsData) {
  console.log('All data loaded');
  displayUserProfile(userData[0], postsData[0], commentsData[0]);
}).fail(function() {
  console.log('One or more requests failed');
});

// Mix different types of values
$.when(
  $.get('/api/data'),
  'immediate value',
  42
).done(function(ajaxResult, stringValue, numberValue) {
  console.log('AJAX:', ajaxResult);
  console.log('String:', stringValue);
  console.log('Number:', numberValue);
});

Additional Core Utilities

Essential utility functions for advanced functionality and cross-browser compatibility.

/**
 * Create proxy function with specific context
 * @param fn - Function to proxy or object with method name
 * @param context - Context object or method name string
 * @returns Proxy function with bound context
 */
$.proxy(fn: function, context: object): function;
$.proxy(context: object, name: string): function;

/**
 * Parse XML string into XML document
 * @param data - XML string to parse
 * @returns XML document or null if parsing fails
 */
$.parseXML(data: string): XMLDocument | null;

/**
 * Release jQuery control of $ variable
 * @param deep - Also release control of jQuery variable
 * @returns jQuery function for reassignment
 */
$.noConflict(deep?: boolean): JQueryStatic;

/**
 * Hold or release jQuery ready event
 * @param hold - Whether to hold (true) or release (false) ready event
 */
$.holdReady(hold: boolean): void;

Usage Examples:

// Proxy function with context
const obj = {
  name: 'MyObject',
  greet: function(message) {
    console.log(this.name + ' says: ' + message);
  }
};

const boundGreet = $.proxy(obj.greet, obj);
boundGreet('Hello!'); // 'MyObject says: Hello!'

// Proxy with method name
const boundMethod = $.proxy(obj, 'greet');
boundMethod('Hi there!'); // 'MyObject says: Hi there!'

// Parse XML
const xmlString = '<root><item id="1">Content</item></root>';
const xmlDoc = $.parseXML(xmlString);
const item = $(xmlDoc).find('item').text(); // 'Content'

// No conflict mode
const jq = $.noConflict();
// Now $ is available for other libraries
// Use jq instead of $ for jQuery
jq('#element').hide();

// Deep no conflict
const jQuery = $.noConflict(true);
// Both $ and jQuery are released
// Use the returned reference
jQuery('#element').show();

// Hold ready event
$.holdReady(true); // Delay ready event
// ... load additional resources ...
$.holdReady(false); // Release ready event

Callback Management

Create and manage callback lists for event-like functionality.

/**
 * Create callback list manager
 * @param flags - Space-separated flags controlling callback behavior
 * @returns Callbacks object
 */
$.Callbacks(flags?: string): JQueryCallbacks;

// Available flags:
// 'once' - Callbacks fire only once
// 'memory' - Remember previous fire values
// 'unique' - Duplicate callbacks are ignored
// 'stopOnFalse' - Stop calling callbacks when one returns false

Usage Examples:

// Basic callback list
const callbacks = $.Callbacks();

callbacks.add(function(value) {
  console.log('Callback 1:', value);
});

callbacks.add(function(value) {
  console.log('Callback 2:', value);
});

callbacks.fire('Hello'); // Both callbacks execute

// Once flag
const onceCallbacks = $.Callbacks('once');
onceCallbacks.add(function() { console.log('Called once'); });
onceCallbacks.fire(); // Logs message
onceCallbacks.fire(); // No output

// Memory flag
const memoryCallbacks = $.Callbacks('memory');
memoryCallbacks.fire('Initial value');
memoryCallbacks.add(function(value) {
  console.log('Late callback:', value); // Immediately fires with 'Initial value'
});

// Unique flag
const uniqueCallbacks = $.Callbacks('unique');
const myFunction = function() { console.log('Unique'); };
uniqueCallbacks.add(myFunction);
uniqueCallbacks.add(myFunction); // Ignored - function already added
uniqueCallbacks.fire(); // Only logs once

// Stop on false flag
const stoppableCallbacks = $.Callbacks('stopOnFalse');
stoppableCallbacks.add(function() { console.log('First'); return true; });
stoppableCallbacks.add(function() { console.log('Second'); return false; });
stoppableCallbacks.add(function() { console.log('Third'); }); // Won't execute
stoppableCallbacks.fire(); // Logs 'First' and 'Second' only