0
# Utility Functions
1
2
Helpful utility functions for array manipulation, string processing, data conversion, and time/date operations to support creative coding workflows.
3
4
## Capabilities
5
6
### Array Functions
7
8
Utility functions for array manipulation and processing.
9
10
```javascript { .api }
11
/**
12
* Add value to end of array
13
* @param {any[]} array - Target array
14
* @param {*} value - Value to append
15
* @returns {any[]} Modified array
16
*/
17
function append(array, value);
18
19
/**
20
* Copy array elements from source to destination
21
* @param {any[]} src - Source array
22
* @param {number} srcPosition - Start index in source
23
* @param {any[]} dst - Destination array
24
* @param {number} dstPosition - Start index in destination
25
* @param {number} length - Number of elements to copy
26
*/
27
function arrayCopy(src, srcPosition, dst, dstPosition, length);
28
29
/**
30
* Concatenate two arrays
31
* @param {any[]} a - First array
32
* @param {any[]} b - Second array
33
* @returns {any[]} Combined array
34
*/
35
function concat(a, b);
36
37
/**
38
* Reverse array order
39
* @param {any[]} list - Array to reverse
40
* @returns {any[]} Reversed array
41
*/
42
function reverse(list);
43
44
/**
45
* Remove last element from array
46
* @param {any[]} list - Target array
47
* @returns {any[]} Shortened array
48
*/
49
function shorten(list);
50
51
/**
52
* Randomize array order
53
* @param {any[]} array - Array to shuffle
54
* @param {boolean} [bool] - Whether to modify original array
55
* @returns {any[]} Shuffled array
56
*/
57
function shuffle(array, bool);
58
59
/**
60
* Sort array elements
61
* @param {any[]} list - Array to sort
62
* @param {number} [count] - Number of elements to sort
63
* @returns {any[]} Sorted array
64
*/
65
function sort(list, count);
66
67
/**
68
* Insert or remove array elements at index
69
* @param {any[]} list - Target array
70
* @param {*} value - Value to insert
71
* @param {number} index - Index for insertion
72
* @returns {any[]} Modified array
73
*/
74
function splice(list, value, index);
75
76
/**
77
* Extract subset of array
78
* @param {any[]} list - Source array
79
* @param {number} start - Start index
80
* @param {number} [count] - Number of elements to extract
81
* @returns {any[]} Array subset
82
*/
83
function subset(list, start, count);
84
```
85
86
### String Functions
87
88
Functions for string manipulation and processing.
89
90
```javascript { .api }
91
/**
92
* Join array elements into string
93
* @param {any[]} list - Array to join
94
* @param {string} separator - Separator string
95
* @returns {string} Joined string
96
*/
97
function join(list, separator);
98
99
/**
100
* Find regex matches in string
101
* @param {string} str - String to search
102
* @param {string} regexp - Regular expression pattern
103
* @returns {string[]|null} Array of matches or null
104
*/
105
function match(str, regexp);
106
107
/**
108
* Find all regex matches in string
109
* @param {string} str - String to search
110
* @param {string} regexp - Regular expression pattern
111
* @returns {string[][]} Array of all matches
112
*/
113
function matchAll(str, regexp);
114
115
/**
116
* Format number as string with specified digits
117
* @param {number} num - Number to format
118
* @param {number} [left] - Digits left of decimal
119
* @param {number} [right] - Digits right of decimal
120
* @returns {string} Formatted number string
121
*/
122
function nf(num, left, right);
123
124
/**
125
* Format number with commas
126
* @param {number} num - Number to format
127
* @param {number} [right] - Digits right of decimal
128
* @returns {string} Formatted number with commas
129
*/
130
function nfc(num, right);
131
132
/**
133
* Format positive number with + sign
134
* @param {number} num - Number to format
135
* @param {number} [left] - Digits left of decimal
136
* @param {number} [right] - Digits right of decimal
137
* @returns {string} Formatted positive number string
138
*/
139
function nfp(num, left, right);
140
141
/**
142
* Format number with + or - sign
143
* @param {number} num - Number to format
144
* @param {number} [left] - Digits left of decimal
145
* @param {number} [right] - Digits right of decimal
146
* @returns {string} Formatted signed number string
147
*/
148
function nfs(num, left, right);
149
150
/**
151
* Split string into array
152
* @param {string} value - String to split
153
* @param {string} delim - Delimiter character
154
* @returns {string[]} Array of substrings
155
*/
156
function split(value, delim);
157
158
/**
159
* Split string by multiple delimiters
160
* @param {string} value - String to split
161
* @param {string} delim - Delimiter characters
162
* @returns {string[]} Array of tokens
163
*/
164
function splitTokens(value, delim);
165
166
/**
167
* Remove whitespace from string ends
168
* @param {string} str - String to trim
169
* @returns {string} Trimmed string
170
*/
171
function trim(str);
172
```
173
174
### Data Conversion Functions
175
176
Functions for converting between different data types.
177
178
```javascript { .api }
179
/**
180
* Convert number to binary string
181
* @param {number} n - Number to convert
182
* @param {number} [digits] - Number of digits in result
183
* @returns {string} Binary string representation
184
*/
185
function binary(n, digits);
186
187
/**
188
* Convert value to boolean
189
* @param {*} n - Value to convert
190
* @returns {boolean} Boolean representation
191
*/
192
function boolean(n);
193
194
/**
195
* Convert number to byte value (0-255)
196
* @param {number} n - Number to convert
197
* @returns {number} Byte value
198
*/
199
function byte(n);
200
201
/**
202
* Convert number to character
203
* @param {number} n - Character code
204
* @returns {string} Character representation
205
*/
206
function char(n);
207
208
/**
209
* Convert string to float
210
* @param {string} str - String to convert
211
* @returns {number} Float value
212
*/
213
function float(str);
214
215
/**
216
* Convert number to hexadecimal string
217
* @param {number} n - Number to convert
218
* @param {number} [digits] - Number of digits in result
219
* @returns {string} Hexadecimal string
220
*/
221
function hex(n, digits);
222
223
/**
224
* Convert string to integer
225
* @param {string} str - String to convert
226
* @param {number} [base] - Number base (default 10)
227
* @returns {number} Integer value
228
*/
229
function int(str, base);
230
231
/**
232
* Convert value to string
233
* @param {*} n - Value to convert
234
* @returns {string} String representation
235
*/
236
function str(n);
237
238
/**
239
* Convert binary string to number
240
* @param {string} str - Binary string
241
* @returns {number} Numeric value
242
*/
243
function unbinary(str);
244
245
/**
246
* Convert hexadecimal string to number
247
* @param {string} str - Hexadecimal string
248
* @returns {number} Numeric value
249
*/
250
function unhex(str);
251
```
252
253
### Time and Date Functions
254
255
Functions for accessing current time and date information.
256
257
```javascript { .api }
258
/**
259
* Get current day of month (1-31)
260
* @returns {number} Current day
261
*/
262
function day();
263
264
/**
265
* Get current hour (0-23)
266
* @returns {number} Current hour
267
*/
268
function hour();
269
270
/**
271
* Get milliseconds since sketch started
272
* @returns {number} Milliseconds elapsed
273
*/
274
function millis();
275
276
/**
277
* Get current minute (0-59)
278
* @returns {number} Current minute
279
*/
280
function minute();
281
282
/**
283
* Get current month (1-12)
284
* @returns {number} Current month
285
*/
286
function month();
287
288
/**
289
* Get current second (0-59)
290
* @returns {number} Current second
291
*/
292
function second();
293
294
/**
295
* Get current year
296
* @returns {number} Current year
297
*/
298
function year();
299
```
300
301
### Local Storage Functions
302
303
Functions for persistent data storage in the web browser's localStorage.
304
305
```javascript { .api }
306
/**
307
* Store a value in browser's local storage
308
* @param {string} key - Name of the value to store
309
* @param {string|number|boolean|object|Array} value - Value to store
310
*/
311
function storeItem(key, value);
312
313
/**
314
* Retrieve a value from browser's local storage
315
* @param {string} key - Name of the value to retrieve
316
* @returns {string|number|boolean|object|Array} Stored value
317
*/
318
function getItem(key);
319
320
/**
321
* Remove all items from browser's local storage
322
*/
323
function clearStorage();
324
325
/**
326
* Remove specific item from browser's local storage
327
* @param {string} key - Name of the value to remove
328
*/
329
function removeItem(key);
330
```
331
332
### Data Structure Functions
333
334
Functions for creating and working with specialized data structures.
335
336
```javascript { .api }
337
/**
338
* Create a new string dictionary
339
* @param {string|object} key - Initial key or object with key-value pairs
340
* @param {string} [value] - Initial value (if key is string)
341
* @returns {p5.StringDict} New string dictionary instance
342
*/
343
function createStringDict(key, value);
344
345
/**
346
* Create a new number dictionary
347
* @param {number|object} key - Initial key or object with key-value pairs
348
* @param {number} [value] - Initial value (if key is number)
349
* @returns {p5.NumberDict} New number dictionary instance
350
*/
351
function createNumberDict(key, value);
352
```
353
354
### Accessibility Functions
355
356
Functions for creating screen reader-accessible descriptions of canvas content.
357
358
```javascript { .api }
359
/**
360
* Create screen reader-accessible description of canvas
361
* @param {string} text - Description of the canvas
362
* @param {constant} [display] - Either LABEL or FALLBACK (default)
363
*/
364
function describe(text, display);
365
366
/**
367
* Create screen reader-accessible description of specific canvas elements
368
* @param {string} name - Name of the element
369
* @param {string} text - Description of the element
370
* @param {constant} [display] - Either LABEL or FALLBACK (default)
371
*/
372
function describeElement(name, text, display);
373
```
374
375
## Usage Examples
376
377
**Array Manipulation:**
378
```javascript
379
let numbers = [1, 2, 3, 4, 5];
380
let colors = ['red', 'green', 'blue'];
381
382
// Add elements
383
numbers = append(numbers, 6);
384
console.log(numbers); // [1, 2, 3, 4, 5, 6]
385
386
// Shuffle array
387
let shuffled = shuffle(colors);
388
console.log(shuffled); // Random order
389
390
// Sort numbers
391
let mixed = [5, 1, 9, 3, 7];
392
let sorted = sort(mixed);
393
console.log(sorted); // [1, 3, 5, 7, 9]
394
395
// Get subset
396
let subset_result = subset(numbers, 2, 3);
397
console.log(subset_result); // [3, 4, 5]
398
```
399
400
**String Processing:**
401
```javascript
402
let sentence = "Hello, World! How are you?";
403
let numbers_list = [1, 2, 3, 4, 5];
404
405
// Split string
406
let words = split(sentence, ' ');
407
console.log(words); // ['Hello,', 'World!', 'How', 'are', 'you?']
408
409
// Join array
410
let joined = join(numbers_list, '-');
411
console.log(joined); // "1-2-3-4-5"
412
413
// Format numbers
414
let pi = 3.14159;
415
console.log(nf(pi, 2, 3)); // "03.142"
416
console.log(nfc(1234.56, 2)); // "1,234.56"
417
console.log(nfp(42)); // "+42"
418
console.log(nfs(-7)); // "-7"
419
420
// Trim whitespace
421
let messy = " Hello World ";
422
console.log(trim(messy)); // "Hello World"
423
```
424
425
**Data Conversion:**
426
```javascript
427
// Number to binary/hex
428
let num = 255;
429
console.log(binary(num)); // "11111111"
430
console.log(hex(num)); // "FF"
431
432
// String to number
433
console.log(int("42")); // 42
434
console.log(float("3.14")); // 3.14
435
console.log(int("1010", 2)); // 10 (binary to decimal)
436
437
// Binary/hex to number
438
console.log(unbinary("1010")); // 10
439
console.log(unhex("FF")); // 255
440
441
// Character conversions
442
console.log(char(65)); // "A"
443
console.log(boolean(1)); // true
444
console.log(boolean(0)); // false
445
```
446
447
**Time-based Animation:**
448
```javascript
449
function draw() {
450
background(220);
451
452
// Get current time
453
let h = hour();
454
let m = minute();
455
let s = second();
456
457
// Display time
458
textSize(24);
459
text(`${h}:${nf(m, 2)}:${nf(s, 2)}`, 50, 50);
460
461
// Animate based on time
462
let seconds_angle = map(s, 0, 59, 0, TWO_PI);
463
let minutes_angle = map(m, 0, 59, 0, TWO_PI);
464
let hours_angle = map(h % 12, 0, 11, 0, TWO_PI);
465
466
translate(width/2, height/2);
467
468
// Draw clock hands
469
stroke('red');
470
strokeWeight(1);
471
line(0, 0, cos(seconds_angle - PI/2) * 80, sin(seconds_angle - PI/2) * 80);
472
473
stroke('blue');
474
strokeWeight(3);
475
line(0, 0, cos(minutes_angle - PI/2) * 60, sin(minutes_angle - PI/2) * 60);
476
477
stroke('black');
478
strokeWeight(5);
479
line(0, 0, cos(hours_angle - PI/2) * 40, sin(hours_angle - PI/2) * 40);
480
481
// Show elapsed time since sketch started
482
resetMatrix();
483
fill('gray');
484
textSize(12);
485
text(`Elapsed: ${millis()}ms`, 10, height - 20);
486
}
487
```
488
489
**Advanced Array Processing:**
490
```javascript
491
function setup() {
492
createCanvas(400, 300);
493
494
// Generate random data
495
let data = [];
496
for (let i = 0; i < 20; i++) {
497
data = append(data, random(100));
498
}
499
500
// Process data
501
let sorted_data = sort(data);
502
let top_values = subset(sorted_data, sorted_data.length - 5, 5);
503
let formatted = [];
504
505
for (let val of top_values) {
506
formatted = append(formatted, nf(val, 3, 2));
507
}
508
509
let result = join(formatted, ', ');
510
console.log(`Top 5 values: ${result}`);
511
512
// Display as bars
513
for (let i = 0; i < data.length; i++) {
514
let x = map(i, 0, data.length - 1, 50, width - 50);
515
let h = map(data[i], 0, 100, 0, height - 100);
516
517
fill(map(data[i], 0, 100, 100, 255), 100, 150);
518
rect(x - 5, height - 50 - h, 10, h);
519
}
520
}
521
```
522
523
**Local Storage:**
524
```javascript
525
function setup() {
526
createCanvas(400, 300);
527
}
528
529
function draw() {
530
background(220);
531
532
// Store player data
533
if (frameCount === 1) {
534
storeItem('playerName', 'Alice');
535
storeItem('score', 1250);
536
storeItem('settings', { volume: 0.8, difficulty: 'medium' });
537
}
538
539
// Retrieve stored data
540
let name = getItem('playerName');
541
let score = getItem('score');
542
let settings = getItem('settings');
543
544
// Display stored information
545
textSize(16);
546
fill('black');
547
text(`Player: ${name}`, 20, 40);
548
text(`Score: ${score}`, 20, 60);
549
text(`Volume: ${settings.volume}`, 20, 80);
550
text(`Difficulty: ${settings.difficulty}`, 20, 100);
551
552
// Instructions
553
textSize(12);
554
fill('gray');
555
text('Press "c" to clear storage, "r" to remove score', 20, height - 40);
556
text('Press "s" to save new score', 20, height - 20);
557
}
558
559
function keyPressed() {
560
if (key === 'c') {
561
clearStorage();
562
console.log('All data cleared');
563
} else if (key === 'r') {
564
removeItem('score');
565
console.log('Score removed');
566
} else if (key === 's') {
567
let newScore = int(random(1000, 5000));
568
storeItem('score', newScore);
569
console.log(`New score saved: ${newScore}`);
570
}
571
}
572
```
573
574
**Data Structures:**
575
```javascript
576
let playerStats;
577
let gameData;
578
579
function setup() {
580
createCanvas(400, 300);
581
582
// Create dictionaries for game data
583
playerStats = createNumberDict('health', 100);
584
playerStats.set('mana', 50);
585
playerStats.set('experience', 1250);
586
587
gameData = createStringDict('playerName', 'Hero');
588
gameData.set('currentLevel', 'Forest');
589
gameData.set('weapon', 'Sword');
590
591
console.log('Player health:', playerStats.get('health'));
592
console.log('Player name:', gameData.get('playerName'));
593
}
594
595
function draw() {
596
background(220);
597
598
// Display player stats
599
textSize(16);
600
fill('black');
601
text('Player Stats:', 20, 30);
602
text(`Health: ${playerStats.get('health')}`, 30, 50);
603
text(`Mana: ${playerStats.get('mana')}`, 30, 70);
604
text(`Experience: ${playerStats.get('experience')}`, 30, 90);
605
606
text('Game Data:', 20, 130);
607
text(`Name: ${gameData.get('playerName')}`, 30, 150);
608
text(`Level: ${gameData.get('currentLevel')}`, 30, 170);
609
text(`Weapon: ${gameData.get('weapon')}`, 30, 190);
610
611
// Show dictionary operations
612
textSize(12);
613
fill('gray');
614
text('Press SPACE to damage player, UP to heal', 20, height - 40);
615
text('Press "l" to level up, "w" to change weapon', 20, height - 20);
616
}
617
618
function keyPressed() {
619
if (key === ' ') {
620
// Take damage
621
let currentHealth = playerStats.get('health');
622
playerStats.set('health', max(0, currentHealth - 10));
623
} else if (keyCode === UP_ARROW) {
624
// Heal
625
let currentHealth = playerStats.get('health');
626
playerStats.set('health', min(100, currentHealth + 15));
627
} else if (key === 'l') {
628
// Level up - gain experience
629
playerStats.add('experience', 100);
630
} else if (key === 'w') {
631
// Change weapon
632
let weapons = ['Sword', 'Bow', 'Staff', 'Dagger'];
633
let currentWeapon = gameData.get('weapon');
634
let currentIndex = weapons.indexOf(currentWeapon);
635
let nextIndex = (currentIndex + 1) % weapons.length;
636
gameData.set('weapon', weapons[nextIndex]);
637
}
638
}
639
```
640
641
**Accessibility:**
642
```javascript
643
function setup() {
644
createCanvas(400, 400);
645
646
// Provide overall description of the canvas
647
describe('Interactive drawing canvas with colorful circles that follow the mouse');
648
}
649
650
function draw() {
651
background(220);
652
653
// Draw main visual elements
654
fill('red');
655
circle(mouseX, mouseY, 60);
656
657
fill('blue');
658
circle(mouseX + 50, mouseY + 50, 40);
659
660
fill('green');
661
circle(mouseX - 50, mouseY - 50, 30);
662
663
// Describe individual elements for screen readers
664
describeElement('MainCircle', `Large red circle at position ${int(mouseX)}, ${int(mouseY)}`);
665
describeElement('BlueCircle', `Medium blue circle offset to bottom-right of red circle`);
666
describeElement('GreenCircle', `Small green circle offset to top-left of red circle`);
667
668
// Add instructions
669
textSize(14);
670
fill('black');
671
text('Move mouse to control circles', 20, height - 40);
672
text('Screen reader users will hear element descriptions', 20, height - 20);
673
}
674
675
function mousePressed() {
676
// Update description when interaction occurs
677
describe(`Canvas with three interactive circles centered at ${int(mouseX)}, ${int(mouseY)}. Click detected.`);
678
}
679
```