or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

component-parser.mdcomponents.mddesign-system.mdduration.mdevents.mdhelpers.mdindex.mdparsing.mdperiod-binary.mdproperties.mdrecurrence.mdtime.mdtimezone.mdvcard-time.md
tile.json

helpers.mddocs/

Helper Utilities

Essential utility functions and helper methods used throughout ICAL.js for string manipulation, object operations, type validation, and debugging. These utilities provide common functionality needed for iCalendar and vCard processing.

Capabilities

Timezone Utilities

Helper functions for timezone and calendar component management.

/**
 * Update timezone components in a calendar
 * @param {ICAL.Component} vcal - VCALENDAR component to update
 * @returns {ICAL.Component} Updated calendar component with timezone definitions
 */
ICAL.helpers.updateTimezones(vcal: ICAL.Component): ICAL.Component;

Usage Examples:

const ICAL = require('ical.js');

// Parse calendar and ensure timezone components are up to date
const vcalendar = new ICAL.Component('vcalendar');
vcalendar.addPropertyWithValue('version', '2.0');

// Add events with timezone references
const event = new ICAL.Component('vevent');
event.addPropertyWithValue('dtstart', ICAL.Time.fromString('20230615T100000', 'America/New_York'));
vcalendar.addSubcomponent(event);

// Update timezone components to ensure all referenced timezones are included
const updatedCalendar = ICAL.helpers.updateTimezones(vcalendar);
console.log('Updated calendar:', updatedCalendar.toString());

Type Validation Utilities

Functions for validating and parsing numeric values with strict error handling.

/**
 * Check if a number is strictly NaN (not just any falsy value)
 * @param {number} number - Number to check
 * @returns {boolean} True if the value is exactly NaN
 */
ICAL.helpers.isStrictlyNaN(number: number): boolean;

/**
 * Parse integer with strict validation
 * @param {string} string - String to parse as integer
 * @returns {number} Parsed integer value
 * @throws {Error} If string cannot be parsed as valid integer
 */
ICAL.helpers.strictParseInt(string: string): number;

/**
 * Format and validate class instances
 * @param {Object} data - Data object to format
 * @param {Function} type - Constructor function for the target type
 * @returns {any} Formatted instance of the specified type
 */
ICAL.helpers.formatClassType(data: Object, type: Function): any;

Usage Examples:

const ICAL = require('ical.js');

// Strict NaN checking
console.log(ICAL.helpers.isStrictlyNaN(NaN));        // true
console.log(ICAL.helpers.isStrictlyNaN(undefined));  // false
console.log(ICAL.helpers.isStrictlyNaN(''));         // false
console.log(ICAL.helpers.isStrictlyNaN(0));          // false

// Strict integer parsing
try {
  const validInt = ICAL.helpers.strictParseInt('42');     // 42
  const invalidInt = ICAL.helpers.strictParseInt('abc');  // throws Error
} catch (error) {
  console.error('Parse error:', error.message);
}

// Class type formatting
const timeData = { year: 2023, month: 6, day: 15 };
const timeInstance = ICAL.helpers.formatClassType(timeData, ICAL.Time);
console.log(timeInstance instanceof ICAL.Time); // true

String Manipulation Utilities

Functions for string processing, escaping, and line formatting specific to iCalendar/vCard formats.

/**
 * Find index of unescaped substring in buffer
 * @param {string} buffer - String to search within
 * @param {string} search - Substring to find
 * @param {number} pos - Starting position for search (optional, default: 0)
 * @returns {number} Index of unescaped substring, or -1 if not found
 */
ICAL.helpers.unescapedIndexOf(buffer: string, search: string, pos?: number): number;

/**
 * Fold long lines according to iCalendar/vCard line folding rules
 * @param {string} line - Line to fold if it exceeds maximum length
 * @returns {string} Folded line with proper continuation characters
 */
ICAL.helpers.foldline(line: string): string;

/**
 * Pad string or number to 2 characters with leading zeros
 * @param {string|number} data - Value to pad
 * @returns {string} Padded string (e.g., '5' becomes '05')
 */
ICAL.helpers.pad2(data: string | number): string;

/**
 * Truncate number towards zero (handles negative numbers correctly)
 * @param {number} number - Number to truncate
 * @returns {number} Truncated number
 */
ICAL.helpers.trunc(number: number): number;

Usage Examples:

const ICAL = require('ical.js');

// Find unescaped substring
const text = 'SUMMARY:Meeting\\, with comma and normal, comma';
const index = ICAL.helpers.unescapedIndexOf(text, ',', 0);
console.log(index); // Position of first unescaped comma

// Fold long lines
const longLine = 'DESCRIPTION:' + 'Very long description text '.repeat(10);
const foldedLine = ICAL.helpers.foldline(longLine);
console.log(foldedLine); // Line folded with \r\n followed by space

// Pad numbers
console.log(ICAL.helpers.pad2(5));   // '05'
console.log(ICAL.helpers.pad2(15));  // '15'
console.log(ICAL.helpers.pad2('7')); // '07'

// Truncate numbers
console.log(ICAL.helpers.trunc(3.7));   // 3
console.log(ICAL.helpers.trunc(-3.7));  // -3
console.log(ICAL.helpers.trunc(0));     // 0

Array and Collection Utilities

Functions for working with arrays and performing binary search operations.

/**
 * Binary search insertion to maintain sorted order
 * @param {Array} list - Sorted array to insert into
 * @param {any} seekVal - Value to insert
 * @param {Function} cmpfunc - Comparison function for sorting
 * @returns {number} Index where value was inserted
 */
ICAL.helpers.binsearchInsert(list: Array, seekVal: any, cmpfunc: Function): number;

Usage Examples:

const ICAL = require('ical.js');

// Binary search insertion for maintaining sorted lists
const sortedTimes = [
  ICAL.Time.fromString('20230601T100000Z'),
  ICAL.Time.fromString('20230610T100000Z'),
  ICAL.Time.fromString('20230620T100000Z')
];

const newTime = ICAL.Time.fromString('20230615T100000Z');

// Insert while maintaining sort order
const insertIndex = ICAL.helpers.binsearchInsert(
  sortedTimes, 
  newTime, 
  function(a, b) { return a.compare(b); }
);

console.log('Inserted at index:', insertIndex); // 2
console.log('Array length:', sortedTimes.length); // 4

// Sort numbers
const numbers = [1, 5, 10, 20];
const insertPos = ICAL.helpers.binsearchInsert(numbers, 15, (a, b) => a - b);
console.log('Numbers after insert:', numbers); // [1, 5, 10, 15, 20]

Object Manipulation Utilities

Functions for cloning objects, inheritance, and object extension.

/**
 * Clone objects and primitives
 * @param {any} src - Source value to clone
 * @param {boolean} deep - Whether to perform deep cloning (optional, default: false)
 * @returns {any} Cloned value
 */
ICAL.helpers.clone(src: any, deep?: boolean): any;

/**
 * Simple inheritance helper
 * @param {Function} base - Base constructor function
 * @param {Function} child - Child constructor function
 * @param {Object} extra - Additional properties to add to child prototype (optional)
 */
ICAL.helpers.inherits(base: Function, child: Function, extra?: Object): void;

/**
 * Extend target object with properties from source object
 * @param {Object} source - Source object to copy properties from
 * @param {Object} target - Target object to copy properties to
 * @returns {Object} Extended target object
 */
ICAL.helpers.extend(source: Object, target: Object): Object;

Usage Examples:

const ICAL = require('ical.js');

// Clone objects
const originalTime = ICAL.Time.fromString('20230615T100000Z');
const shallowClone = ICAL.helpers.clone(originalTime, false);
const deepClone = ICAL.helpers.clone(originalTime, true);

// Clone primitive values
const clonedString = ICAL.helpers.clone('hello'); // 'hello'
const clonedNumber = ICAL.helpers.clone(42);      // 42

// Simple inheritance
function BaseClass() {
  this.baseProp = 'base';
}
BaseClass.prototype.baseMethod = function() {
  return 'base method';
};

function ChildClass() {
  BaseClass.call(this);
  this.childProp = 'child';
}

ICAL.helpers.inherits(BaseClass, ChildClass, {
  childMethod: function() {
    return 'child method';
  }
});

const instance = new ChildClass();
console.log(instance.baseProp);     // 'base'
console.log(instance.childProp);    // 'child'
console.log(instance.baseMethod()); // 'base method'
console.log(instance.childMethod()); // 'child method'

// Extend objects
const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
const extended = ICAL.helpers.extend(source, target);
console.log(extended); // { a: 1, b: 3, c: 4 }

Debug Utilities

Functions for debugging and development support.

/**
 * Debug output function (only active when ICAL.debug is enabled)
 * @param {any} input - Value to output for debugging
 */
ICAL.helpers.dumpn(input: any): void;

Usage Examples:

const ICAL = require('ical.js');

// Enable debug mode (if supported in environment)
if (typeof ICAL.debug !== 'undefined') {
  ICAL.debug = true;
}

// Debug output (only shows when debug mode is enabled)
ICAL.helpers.dumpn('Debug message');
ICAL.helpers.dumpn({ debug: 'object', values: [1, 2, 3] });

// Debug complex structures
const component = new ICAL.Component('vevent');
component.addPropertyWithValue('summary', 'Debug Event');
ICAL.helpers.dumpn(component.toString());

Global Configuration Constants

The helpers module also manages global configuration values used throughout ICAL.js:

// Line folding character limit (default: 75)
ICAL.foldLength: number;

// Newline characters used in output (default: "\r\n")
ICAL.newLineChar: string;

Usage Examples:

const ICAL = require('ical.js');

// Check current configuration
console.log('Fold length:', ICAL.foldLength);     // 75
console.log('Newline char:', ICAL.newLineChar);   // "\r\n"

// Modify folding behavior (if needed)
ICAL.foldLength = 72; // Shorter lines
ICAL.newLineChar = '\n'; // Unix-style newlines

// Create content that uses these settings
const longProperty = 'DESCRIPTION:' + 'Very long text '.repeat(20);
const folded = ICAL.helpers.foldline(longProperty);
console.log('Uses custom fold length and newline chars');

Integration with Core Classes

Helper functions are used internally throughout ICAL.js classes but can also be useful in application code:

const ICAL = require('ical.js');

// Example: Custom component validation
function validateComponent(component) {
  // Use type validation
  if (ICAL.helpers.isStrictlyNaN(component.getFirstPropertyValue('sequence'))) {
    throw new Error('Invalid sequence number');
  }
  
  // Use string utilities for property processing
  const summary = component.getFirstPropertyValue('summary') || '';
  const unescapedCommaIndex = ICAL.helpers.unescapedIndexOf(summary, ',');
  
  if (unescapedCommaIndex !== -1) {
    console.log('Summary contains unescaped comma at position:', unescapedCommaIndex);
  }
  
  return true;
}

// Example: Custom time processing with helpers
function processTimeList(times) {
  // Clone the input to avoid mutation
  const processedTimes = ICAL.helpers.clone(times, true);
  
  // Sort times using binary search insertion
  const sortedTimes = [];
  for (const time of processedTimes) {
    ICAL.helpers.binsearchInsert(sortedTimes, time, (a, b) => a.compare(b));
  }
  
  return sortedTimes;
}