CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-p5

A free and open-source JavaScript library for accessible creative coding

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

utilities.mddocs/

Utility Functions

Helpful utility functions for array manipulation, string processing, data conversion, and time/date operations to support creative coding workflows.

Capabilities

Array Functions

Utility functions for array manipulation and processing.

/**
 * Add value to end of array
 * @param {any[]} array - Target array
 * @param {*} value - Value to append
 * @returns {any[]} Modified array
 */
function append(array, value);

/**
 * Copy array elements from source to destination
 * @param {any[]} src - Source array
 * @param {number} srcPosition - Start index in source
 * @param {any[]} dst - Destination array
 * @param {number} dstPosition - Start index in destination
 * @param {number} length - Number of elements to copy
 */
function arrayCopy(src, srcPosition, dst, dstPosition, length);

/**
 * Concatenate two arrays
 * @param {any[]} a - First array
 * @param {any[]} b - Second array
 * @returns {any[]} Combined array
 */
function concat(a, b);

/**
 * Reverse array order
 * @param {any[]} list - Array to reverse
 * @returns {any[]} Reversed array
 */
function reverse(list);

/**
 * Remove last element from array
 * @param {any[]} list - Target array
 * @returns {any[]} Shortened array
 */
function shorten(list);

/**
 * Randomize array order
 * @param {any[]} array - Array to shuffle
 * @param {boolean} [bool] - Whether to modify original array
 * @returns {any[]} Shuffled array
 */
function shuffle(array, bool);

/**
 * Sort array elements
 * @param {any[]} list - Array to sort
 * @param {number} [count] - Number of elements to sort
 * @returns {any[]} Sorted array
 */
function sort(list, count);

/**
 * Insert or remove array elements at index
 * @param {any[]} list - Target array
 * @param {*} value - Value to insert
 * @param {number} index - Index for insertion
 * @returns {any[]} Modified array
 */
function splice(list, value, index);

/**
 * Extract subset of array
 * @param {any[]} list - Source array
 * @param {number} start - Start index
 * @param {number} [count] - Number of elements to extract
 * @returns {any[]} Array subset
 */
function subset(list, start, count);

String Functions

Functions for string manipulation and processing.

/**
 * Join array elements into string
 * @param {any[]} list - Array to join
 * @param {string} separator - Separator string
 * @returns {string} Joined string
 */
function join(list, separator);

/**
 * Find regex matches in string
 * @param {string} str - String to search
 * @param {string} regexp - Regular expression pattern
 * @returns {string[]|null} Array of matches or null
 */
function match(str, regexp);

/**
 * Find all regex matches in string
 * @param {string} str - String to search
 * @param {string} regexp - Regular expression pattern
 * @returns {string[][]} Array of all matches
 */
function matchAll(str, regexp);

/**
 * Format number as string with specified digits
 * @param {number} num - Number to format
 * @param {number} [left] - Digits left of decimal
 * @param {number} [right] - Digits right of decimal
 * @returns {string} Formatted number string
 */
function nf(num, left, right);

/**
 * Format number with commas
 * @param {number} num - Number to format
 * @param {number} [right] - Digits right of decimal
 * @returns {string} Formatted number with commas
 */
function nfc(num, right);

/**
 * Format positive number with + sign
 * @param {number} num - Number to format
 * @param {number} [left] - Digits left of decimal
 * @param {number} [right] - Digits right of decimal
 * @returns {string} Formatted positive number string
 */
function nfp(num, left, right);

/**
 * Format number with + or - sign
 * @param {number} num - Number to format
 * @param {number} [left] - Digits left of decimal
 * @param {number} [right] - Digits right of decimal
 * @returns {string} Formatted signed number string
 */
function nfs(num, left, right);

/**
 * Split string into array
 * @param {string} value - String to split
 * @param {string} delim - Delimiter character
 * @returns {string[]} Array of substrings
 */
function split(value, delim);

/**
 * Split string by multiple delimiters
 * @param {string} value - String to split
 * @param {string} delim - Delimiter characters
 * @returns {string[]} Array of tokens
 */
function splitTokens(value, delim);

/**
 * Remove whitespace from string ends
 * @param {string} str - String to trim
 * @returns {string} Trimmed string
 */
function trim(str);

Data Conversion Functions

Functions for converting between different data types.

/**
 * Convert number to binary string
 * @param {number} n - Number to convert
 * @param {number} [digits] - Number of digits in result
 * @returns {string} Binary string representation
 */
function binary(n, digits);

/**
 * Convert value to boolean
 * @param {*} n - Value to convert
 * @returns {boolean} Boolean representation
 */
function boolean(n);

/**
 * Convert number to byte value (0-255)
 * @param {number} n - Number to convert
 * @returns {number} Byte value
 */
function byte(n);

/**
 * Convert number to character
 * @param {number} n - Character code
 * @returns {string} Character representation
 */
function char(n);

/**
 * Convert string to float
 * @param {string} str - String to convert
 * @returns {number} Float value
 */
function float(str);

/**
 * Convert number to hexadecimal string
 * @param {number} n - Number to convert
 * @param {number} [digits] - Number of digits in result
 * @returns {string} Hexadecimal string
 */
function hex(n, digits);

/**
 * Convert string to integer
 * @param {string} str - String to convert
 * @param {number} [base] - Number base (default 10)
 * @returns {number} Integer value
 */
function int(str, base);

/**
 * Convert value to string
 * @param {*} n - Value to convert
 * @returns {string} String representation
 */
function str(n);

/**
 * Convert binary string to number
 * @param {string} str - Binary string
 * @returns {number} Numeric value
 */
function unbinary(str);

/**
 * Convert hexadecimal string to number
 * @param {string} str - Hexadecimal string
 * @returns {number} Numeric value
 */
function unhex(str);

Time and Date Functions

Functions for accessing current time and date information.

/**
 * Get current day of month (1-31)
 * @returns {number} Current day
 */
function day();

/**
 * Get current hour (0-23)
 * @returns {number} Current hour
 */
function hour();

/**
 * Get milliseconds since sketch started
 * @returns {number} Milliseconds elapsed
 */
function millis();

/**
 * Get current minute (0-59)
 * @returns {number} Current minute
 */
function minute();

/**
 * Get current month (1-12)
 * @returns {number} Current month
 */
function month();

/**
 * Get current second (0-59)
 * @returns {number} Current second
 */
function second();

/**
 * Get current year
 * @returns {number} Current year
 */
function year();

Local Storage Functions

Functions for persistent data storage in the web browser's localStorage.

/**
 * Store a value in browser's local storage
 * @param {string} key - Name of the value to store
 * @param {string|number|boolean|object|Array} value - Value to store
 */
function storeItem(key, value);

/**
 * Retrieve a value from browser's local storage
 * @param {string} key - Name of the value to retrieve
 * @returns {string|number|boolean|object|Array} Stored value
 */
function getItem(key);

/**
 * Remove all items from browser's local storage
 */
function clearStorage();

/**
 * Remove specific item from browser's local storage
 * @param {string} key - Name of the value to remove
 */
function removeItem(key);

Data Structure Functions

Functions for creating and working with specialized data structures.

/**
 * Create a new string dictionary
 * @param {string|object} key - Initial key or object with key-value pairs
 * @param {string} [value] - Initial value (if key is string)
 * @returns {p5.StringDict} New string dictionary instance
 */
function createStringDict(key, value);

/**
 * Create a new number dictionary
 * @param {number|object} key - Initial key or object with key-value pairs
 * @param {number} [value] - Initial value (if key is number)
 * @returns {p5.NumberDict} New number dictionary instance
 */
function createNumberDict(key, value);

Accessibility Functions

Functions for creating screen reader-accessible descriptions of canvas content.

/**
 * Create screen reader-accessible description of canvas
 * @param {string} text - Description of the canvas
 * @param {constant} [display] - Either LABEL or FALLBACK (default)
 */
function describe(text, display);

/**
 * Create screen reader-accessible description of specific canvas elements
 * @param {string} name - Name of the element
 * @param {string} text - Description of the element
 * @param {constant} [display] - Either LABEL or FALLBACK (default)
 */
function describeElement(name, text, display);

Usage Examples

Array Manipulation:

let numbers = [1, 2, 3, 4, 5];
let colors = ['red', 'green', 'blue'];

// Add elements
numbers = append(numbers, 6);
console.log(numbers); // [1, 2, 3, 4, 5, 6]

// Shuffle array
let shuffled = shuffle(colors);
console.log(shuffled); // Random order

// Sort numbers
let mixed = [5, 1, 9, 3, 7];
let sorted = sort(mixed);
console.log(sorted); // [1, 3, 5, 7, 9]

// Get subset
let subset_result = subset(numbers, 2, 3);
console.log(subset_result); // [3, 4, 5]

String Processing:

let sentence = "Hello, World! How are you?";
let numbers_list = [1, 2, 3, 4, 5];

// Split string
let words = split(sentence, ' ');
console.log(words); // ['Hello,', 'World!', 'How', 'are', 'you?']

// Join array
let joined = join(numbers_list, '-');
console.log(joined); // "1-2-3-4-5"

// Format numbers
let pi = 3.14159;
console.log(nf(pi, 2, 3)); // "03.142"
console.log(nfc(1234.56, 2)); // "1,234.56"
console.log(nfp(42)); // "+42"
console.log(nfs(-7)); // "-7"

// Trim whitespace
let messy = "  Hello World  ";
console.log(trim(messy)); // "Hello World"

Data Conversion:

// Number to binary/hex
let num = 255;
console.log(binary(num)); // "11111111"
console.log(hex(num)); // "FF"

// String to number
console.log(int("42")); // 42
console.log(float("3.14")); // 3.14
console.log(int("1010", 2)); // 10 (binary to decimal)

// Binary/hex to number
console.log(unbinary("1010")); // 10
console.log(unhex("FF")); // 255

// Character conversions
console.log(char(65)); // "A"
console.log(boolean(1)); // true
console.log(boolean(0)); // false

Time-based Animation:

function draw() {
  background(220);
  
  // Get current time
  let h = hour();
  let m = minute();
  let s = second();
  
  // Display time
  textSize(24);
  text(`${h}:${nf(m, 2)}:${nf(s, 2)}`, 50, 50);
  
  // Animate based on time
  let seconds_angle = map(s, 0, 59, 0, TWO_PI);
  let minutes_angle = map(m, 0, 59, 0, TWO_PI);
  let hours_angle = map(h % 12, 0, 11, 0, TWO_PI);
  
  translate(width/2, height/2);
  
  // Draw clock hands
  stroke('red');
  strokeWeight(1);
  line(0, 0, cos(seconds_angle - PI/2) * 80, sin(seconds_angle - PI/2) * 80);
  
  stroke('blue');
  strokeWeight(3);
  line(0, 0, cos(minutes_angle - PI/2) * 60, sin(minutes_angle - PI/2) * 60);
  
  stroke('black');
  strokeWeight(5);
  line(0, 0, cos(hours_angle - PI/2) * 40, sin(hours_angle - PI/2) * 40);
  
  // Show elapsed time since sketch started
  resetMatrix();
  fill('gray');
  textSize(12);
  text(`Elapsed: ${millis()}ms`, 10, height - 20);
}

Advanced Array Processing:

function setup() {
  createCanvas(400, 300);
  
  // Generate random data
  let data = [];
  for (let i = 0; i < 20; i++) {
    data = append(data, random(100));
  }
  
  // Process data
  let sorted_data = sort(data);
  let top_values = subset(sorted_data, sorted_data.length - 5, 5);
  let formatted = [];
  
  for (let val of top_values) {
    formatted = append(formatted, nf(val, 3, 2));
  }
  
  let result = join(formatted, ', ');
  console.log(`Top 5 values: ${result}`);
  
  // Display as bars
  for (let i = 0; i < data.length; i++) {
    let x = map(i, 0, data.length - 1, 50, width - 50);
    let h = map(data[i], 0, 100, 0, height - 100);
    
    fill(map(data[i], 0, 100, 100, 255), 100, 150);
    rect(x - 5, height - 50 - h, 10, h);
  }
}

Local Storage:

function setup() {
  createCanvas(400, 300);
}

function draw() {
  background(220);
  
  // Store player data
  if (frameCount === 1) {
    storeItem('playerName', 'Alice');
    storeItem('score', 1250);
    storeItem('settings', { volume: 0.8, difficulty: 'medium' });
  }
  
  // Retrieve stored data
  let name = getItem('playerName');
  let score = getItem('score');
  let settings = getItem('settings');
  
  // Display stored information
  textSize(16);
  fill('black');
  text(`Player: ${name}`, 20, 40);
  text(`Score: ${score}`, 20, 60);
  text(`Volume: ${settings.volume}`, 20, 80);
  text(`Difficulty: ${settings.difficulty}`, 20, 100);
  
  // Instructions
  textSize(12);
  fill('gray');
  text('Press "c" to clear storage, "r" to remove score', 20, height - 40);
  text('Press "s" to save new score', 20, height - 20);
}

function keyPressed() {
  if (key === 'c') {
    clearStorage();
    console.log('All data cleared');
  } else if (key === 'r') {
    removeItem('score');
    console.log('Score removed');
  } else if (key === 's') {
    let newScore = int(random(1000, 5000));
    storeItem('score', newScore);
    console.log(`New score saved: ${newScore}`);
  }
}

Data Structures:

let playerStats;
let gameData;

function setup() {
  createCanvas(400, 300);
  
  // Create dictionaries for game data
  playerStats = createNumberDict('health', 100);
  playerStats.set('mana', 50);
  playerStats.set('experience', 1250);
  
  gameData = createStringDict('playerName', 'Hero');
  gameData.set('currentLevel', 'Forest');
  gameData.set('weapon', 'Sword');
  
  console.log('Player health:', playerStats.get('health'));
  console.log('Player name:', gameData.get('playerName'));
}

function draw() {
  background(220);
  
  // Display player stats
  textSize(16);
  fill('black');
  text('Player Stats:', 20, 30);
  text(`Health: ${playerStats.get('health')}`, 30, 50);
  text(`Mana: ${playerStats.get('mana')}`, 30, 70);
  text(`Experience: ${playerStats.get('experience')}`, 30, 90);
  
  text('Game Data:', 20, 130);
  text(`Name: ${gameData.get('playerName')}`, 30, 150);
  text(`Level: ${gameData.get('currentLevel')}`, 30, 170);
  text(`Weapon: ${gameData.get('weapon')}`, 30, 190);
  
  // Show dictionary operations
  textSize(12);
  fill('gray');
  text('Press SPACE to damage player, UP to heal', 20, height - 40);
  text('Press "l" to level up, "w" to change weapon', 20, height - 20);
}

function keyPressed() {
  if (key === ' ') {
    // Take damage
    let currentHealth = playerStats.get('health');
    playerStats.set('health', max(0, currentHealth - 10));
  } else if (keyCode === UP_ARROW) {
    // Heal
    let currentHealth = playerStats.get('health');
    playerStats.set('health', min(100, currentHealth + 15));
  } else if (key === 'l') {
    // Level up - gain experience
    playerStats.add('experience', 100);
  } else if (key === 'w') {
    // Change weapon
    let weapons = ['Sword', 'Bow', 'Staff', 'Dagger'];
    let currentWeapon = gameData.get('weapon');
    let currentIndex = weapons.indexOf(currentWeapon);
    let nextIndex = (currentIndex + 1) % weapons.length;
    gameData.set('weapon', weapons[nextIndex]);
  }
}

Accessibility:

function setup() {
  createCanvas(400, 400);
  
  // Provide overall description of the canvas
  describe('Interactive drawing canvas with colorful circles that follow the mouse');
}

function draw() {
  background(220);
  
  // Draw main visual elements
  fill('red');
  circle(mouseX, mouseY, 60);
  
  fill('blue');
  circle(mouseX + 50, mouseY + 50, 40);
  
  fill('green');
  circle(mouseX - 50, mouseY - 50, 30);
  
  // Describe individual elements for screen readers
  describeElement('MainCircle', `Large red circle at position ${int(mouseX)}, ${int(mouseY)}`);
  describeElement('BlueCircle', `Medium blue circle offset to bottom-right of red circle`);
  describeElement('GreenCircle', `Small green circle offset to top-left of red circle`);
  
  // Add instructions
  textSize(14);
  fill('black');
  text('Move mouse to control circles', 20, height - 40);
  text('Screen reader users will hear element descriptions', 20, height - 20);
}

function mousePressed() {
  // Update description when interaction occurs
  describe(`Canvas with three interactive circles centered at ${int(mouseX)}, ${int(mouseY)}. Click detected.`);
}

Install with Tessl CLI

npx tessl i tessl/npm-p5

docs

color-system.md

core-structure.md

dom-manipulation.md

drawing-shapes.md

events-input.md

image-processing.md

index.md

io-data.md

math-vectors.md

transforms.md

typography.md

utilities.md

webgl-3d.md

tile.json