
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
wavefuel-utils
Advanced tools
Represents a singly linked list.
Kind: global class
numberbooleanbooleanT | nullbooleanArray.<T>numberReturns the number of elements in the linked list.
Kind: instance property of LinkedList
Returns: number - The number of elements in the linked list.
Example
const list = new LinkedList();
list.append(1);
list.append(2);
const size = list.size;
console.log(size); // Output: 2
Appends a new element to the end of the linked list.
Kind: instance method of LinkedList
| Param | Type | Description |
|---|---|---|
| value | T | The value to append. |
Example
const list = new LinkedList();
list.append(1);
list.append(2);
console.log(list.toArray()); // Output: [1, 2]
Prepends a new element to the beginning of the linked list.
Kind: instance method of LinkedList
| Param | Type | Description |
|---|---|---|
| value | T | The value to prepend. |
Example
const list = new LinkedList();
list.prepend(1);
list.prepend(2);
console.log(list.toArray()); // Output: [2, 1]
booleanInserts a new element after a given element in the linked list.
Kind: instance method of LinkedList
Returns: boolean - true if the insertion is successful, false if the target element is not found.
| Param | Type | Description |
|---|---|---|
| value | T | The value to insert. |
| target | T | The element after which the new value should be inserted. |
Example
const list = new LinkedList();
list.append(1);
list.append(2);
list.insertAfter(3, 1);
console.log(list.toArray()); // Output: [1, 3, 2]
booleanRemoves the first occurrence of a specified element from the linked list.
Kind: instance method of LinkedList
Returns: boolean - true if the removal is successful, false if the element is not found.
| Param | Type | Description |
|---|---|---|
| value | T | The value to remove. |
Example
const list = new LinkedList();
list.append(1);
list.append(2);
list.remove(1);
console.log(list.toArray()); // Output: [2]
T | nullFinds the first occurrence of a specified element in the linked list.
Kind: instance method of LinkedList
Returns: T | null - The found element, or null if not found.
| Param | Type | Description |
|---|---|---|
| value | T | The value to find. |
Example
const list = new LinkedList();
list.append(1);
list.append(2);
const foundValue = list.find(2);
console.log(foundValue); // Output: 2
booleanChecks if the linked list is empty.
Kind: instance method of LinkedList
Returns: boolean - true if the linked list is empty, false otherwise.
Example
const list = new LinkedList();
console.log(list.isEmpty()); // Output: true
list.append(1);
console.log(list.isEmpty()); // Output: false
Array.<T>Converts the linked list to an array.
Kind: instance method of LinkedList
Returns: Array.<T> - An array containing all elements of the linked list in order.
Example
const list = new LinkedList();
list.append(1);
list.append(2);
const array = list.toArray();
console.log(array); // Output: [1, 2]
Clears all elements from the linked list.
Kind: instance method of LinkedList
Example
const list = new LinkedList();
list.append(1);
list.append(2);
list.clear();
console.log(list.toArray()); // Output: []
console.log(list.size); // Output: 0
Represents a stack data structure.
Kind: global class
T | undefinedT | undefinedbooleannumberArray.<T>Pushes an element onto the top of the stack.
Kind: instance method of Stack
| Param | Type | Description |
|---|---|---|
| element | T | The element to push onto the stack. |
Example
const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.toArray()); // Output: [1, 2]
T | undefinedRemoves and returns the top element from the stack.
Kind: instance method of Stack
Returns: T | undefined - The top element of the stack, or undefined if the stack is empty.
Example
const stack = new Stack();
stack.push(1);
stack.push(2);
const poppedElement = stack.pop();
console.log(poppedElement); // Output: 2
console.log(stack.toArray()); // Output: [1]
T | undefinedReturns the top element of the stack without removing it.
Kind: instance method of Stack
Returns: T | undefined - The top element of the stack, or undefined if the stack is empty.
Example
const stack = new Stack();
stack.push(1);
stack.push(2);
const topElement = stack.peek();
console.log(topElement); // Output: 2
console.log(stack.toArray()); // Output: [1, 2]
booleanChecks if the stack is empty.
Kind: instance method of Stack
Returns: boolean - true if the stack is empty, false otherwise.
Example
const stack = new Stack();
console.log(stack.isEmpty()); // Output: true
stack.push(1);
console.log(stack.isEmpty()); // Output: false
numberReturns the number of elements in the stack.
Kind: instance method of Stack
Returns: number - The number of elements in the stack.
Example
const stack = new Stack();
stack.push(1);
stack.push(2);
const size = stack.size();
console.log(size); // Output: 2
Clears all elements from the stack.
Kind: instance method of Stack
Example
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.clear();
console.log(stack.toArray()); // Output: []
console.log(stack.size()); // Output: 0
Array.<T>Converts the stack to an array.
Kind: instance method of Stack
Returns: Array.<T> - An array containing all elements of the stack in order from top to bottom.
Example
const stack = new Stack();
stack.push(1);
stack.push(2);
const array = stack.toArray();
console.log(array); // Output: [2, 1]
Represents a queue data structure.
Kind: global class
T | undefinedT | undefinedbooleannumberArray.<T>Adds an element to the back of the queue.
Kind: instance method of Queue
| Param | Type | Description |
|---|---|---|
| element | T | The element to enqueue. |
Example
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.toArray()); // Output: [1, 2]
T | undefinedRemoves and returns the front element from the queue.
Kind: instance method of Queue
Returns: T | undefined - The front element of the queue, or undefined if the queue is empty.
Example
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
const dequeuedElement = queue.dequeue();
console.log(dequeuedElement); // Output: 1
console.log(queue.toArray()); // Output: [2]
T | undefinedReturns the front element of the queue without removing it.
Kind: instance method of Queue
Returns: T | undefined - The front element of the queue, or undefined if the queue is empty.
Example
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
const frontElement = queue.peek();
console.log(frontElement); // Output: 1
console.log(queue.toArray()); // Output: [1, 2]
booleanChecks if the queue is empty.
Kind: instance method of Queue
Returns: boolean - true if the queue is empty, false otherwise.
Example
const queue = new Queue();
console.log(queue.isEmpty()); // Output: true
queue.enqueue(1);
console.log(queue.isEmpty()); // Output: false
numberReturns the number of elements in the queue.
Kind: instance method of Queue
Returns: number - The number of elements in the queue.
Example
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
const size = queue.size();
console.log(size); // Output: 2
Clears all elements from the queue.
Kind: instance method of Queue
Example
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.clear();
console.log(queue.toArray()); // Output: []
console.log(queue.size()); // Output: 0
Array.<T>Converts the queue to an array.
Kind: instance method of Queue
Returns: Array.<T> - An array containing all elements of the queue in order from front to back.
Example
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
const array = queue.toArray();
console.log(array); // Output: [1, 2]
Represents a node in a binary search tree.
Represents a binary search tree.
Kind: global class
booleanT | nullT | nullnumberArray.<T>Array.<T>Array.<T>Inserts a new element into the binary search tree.
Kind: instance method of BinarySearchTree
| Param | Type | Description |
|---|---|---|
| value | T | The value to insert. |
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.find(3)); // Output: true
console.log(bst.find(6)); // Output: false
Deletes an element from the binary search tree.
Kind: instance method of BinarySearchTree
| Param | Type | Description |
|---|---|---|
| value | T | The value to delete. |
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
bst.delete(3);
console.log(bst.find(3)); // Output: false
booleanFinds an element in the binary search tree.
Kind: instance method of BinarySearchTree
Returns: boolean - true if the element is found, false otherwise.
| Param | Type | Description |
|---|---|---|
| value | T | The value to find. |
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.find(3)); // Output: true
console.log(bst.find(6)); // Output: false
T | nullGets the minimum element in the binary search tree.
Kind: instance method of BinarySearchTree
Returns: T | null - The minimum element, or null if the tree is empty.
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.getMin()); // Output: 3
T | nullGets the maximum element in the binary search tree.
Kind: instance method of BinarySearchTree
Returns: T | null - The maximum element, or null if the tree is empty.
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.getMax()); // Output: 8
numberGets the height of the binary search tree.
Kind: instance method of BinarySearchTree
Returns: number - The height of the tree.
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.getHeight()); // Output: 2
Array.<T>Traverses the binary search tree in in-order and returns the elements in an array.
Kind: instance method of BinarySearchTree
Returns: Array.<T> - An array containing elements of the tree in in-order.
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.traverseInOrder()); // Output: [3, 5, 8]
Array.<T>Traverses the binary search tree in pre-order and returns the elements in an array.
Kind: instance method of BinarySearchTree
Returns: Array.<T> - An array containing elements of the tree in pre-order.
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.traversePreOrder()); // Output: [5, 3, 8]
Array.<T>Traverses the binary search tree in post-order and returns the elements in an array.
Kind: instance method of BinarySearchTree
Returns: Array.<T> - An array containing elements of the tree in post-order.
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.traversePostOrder()); // Output: [3, 8, 5]
Represents a vertex in an undirected graph.
Represents an undirected graph.
Kind: global class
booleanbooleanArray.<T>Adds a new vertex to the graph.
Kind: instance method of UndirectedGraph
| Param | Type | Description |
|---|---|---|
| value | T | The value to associate with the new vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
Removes a vertex and all its edges from the graph.
Kind: instance method of UndirectedGraph
| Param | Type | Description |
|---|---|---|
| value | T | The value associated with the vertex to remove. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');
graph.removeVertex('A');
Adds an edge between two vertices in the graph.
Kind: instance method of UndirectedGraph
| Param | Type | Description |
|---|---|---|
| value1 | T | The value associated with the first vertex. |
| value2 | T | The value associated with the second vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');
Removes an edge between two vertices in the graph.
Kind: instance method of UndirectedGraph
| Param | Type | Description |
|---|---|---|
| value1 | T | The value associated with the first vertex. |
| value2 | T | The value associated with the second vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');
graph.removeEdge('A', 'B');
booleanChecks if a vertex with a given value exists in the graph.
Kind: instance method of UndirectedGraph
Returns: boolean - true if the vertex exists, false otherwise.
| Param | Type | Description |
|---|---|---|
| value | T | The value associated with the vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
console.log(graph.hasVertex('A')); // Output: true
console.log(graph.hasVertex('B')); // Output: false
booleanChecks if an edge exists between two vertices in the graph.
Kind: instance method of UndirectedGraph
Returns: boolean - true if the edge exists, false otherwise.
| Param | Type | Description |
|---|---|---|
| value1 | T | The value associated with the first vertex. |
| value2 | T | The value associated with the second vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');
console.log(graph.hasEdge('A', 'B')); // Output: true
console.log(graph.hasEdge('A', 'C')); // Output: false
Array.<T>Gets an array of neighbors for a given vertex.
Kind: instance method of UndirectedGraph
Returns: Array.<T> - An array of neighbor values.
| Param | Type | Description |
|---|---|---|
| value | T | The value associated with the vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');
graph.addEdge('A', 'B');
graph.addEdge('A', 'C');
console.log(graph.getNeighbors('A')); // Output: ['B', 'C']
Represents a key-value pair in a hash table.
Represents a hash table.
Kind: global class
V | undefinedbooleanArray.<K>Array.<V>Inserts a key-value pair into the hash table.
Kind: instance method of HashTable
| Param | Type | Description |
|---|---|---|
| key | K | The key to insert. |
| value | V | The value to insert. |
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
hashTable.put('banana', 8);
V | undefinedRetrieves the value associated with a key from the hash table.
Kind: instance method of HashTable
Returns: V | undefined - The value associated with the key, or undefined if not found.
| Param | Type | Description |
|---|---|---|
| key | K | The key to search for. |
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
console.log(hashTable.get('apple')); // Output: 5
console.log(hashTable.get('banana')); // Output: undefined
Removes a key-value pair associated with a key from the hash table.
Kind: instance method of HashTable
| Param | Type | Description |
|---|---|---|
| key | K | The key to remove. |
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
hashTable.remove('apple');
console.log(hashTable.get('apple')); // Output: undefined
booleanChecks if the hash table contains a key.
Kind: instance method of HashTable
Returns: boolean - true if the key exists, false otherwise.
| Param | Type | Description |
|---|---|---|
| key | K | The key to check. |
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
console.log(hashTable.containsKey('apple')); // Output: true
console.log(hashTable.containsKey('banana')); // Output: false
Array.<K>Retrieves an array of keys in the hash table.
Kind: instance method of HashTable
Returns: Array.<K> - An array of keys in the hash table.
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
hashTable.put('banana', 8);
console.log(hashTable.keys()); // Output: ['apple', 'banana']
Array.<V>Retrieves an array of values in the hash table.
Kind: instance method of HashTable
Returns: Array.<V> - An array of values in the hash table.
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
hashTable.put('banana', 8);
console.log(hashTable.values()); // Output: [5, 8]
Represents a node in a B-Tree.
Represents a node in a Trie.
Represents a Trie (prefix tree).
Kind: global class
booleanbooleanArray.<string>Inserts a word into the Trie.
Kind: instance method of Trie
| Param | Type | Description |
|---|---|---|
| word | string | The word to insert. |
Example
const trie = new Trie();
trie.insert("apple");
trie.insert("app");
booleanSearches for a word in the Trie.
Kind: instance method of Trie
Returns: boolean - true if the word is found, false otherwise.
| Param | Type | Description |
|---|---|---|
| word | string | The word to search for. |
Example
const trie = new Trie();
trie.insert("apple");
console.log(trie.search("apple")); // Output: true
console.log(trie.search("app")); // Output: false
booleanDetermines if there are any words in the Trie that start with a given prefix.
Kind: instance method of Trie
Returns: boolean - true if there are words with the given prefix, false otherwise.
| Param | Type | Description |
|---|---|---|
| prefix | string | The prefix to check. |
Example
const trie = new Trie();
trie.insert("apple");
console.log(trie.startsWith("app")); // Output: true
console.log(trie.startsWith("ban")); // Output: false
Deletes a word from the Trie.
Kind: instance method of Trie
| Param | Type | Description |
|---|---|---|
| word | string | The word to delete. |
Example
const trie = new Trie();
trie.insert("apple");
trie.delete("apple");
console.log(trie.search("apple")); // Output: false
Array.<string>Returns a list of words in the Trie that start with a given prefix.
Kind: instance method of Trie
Returns: Array.<string> - An array of autocompleted words.
| Param | Type | Description |
|---|---|---|
| prefix | string | The prefix to autocomplete. |
Example
const trie = new Trie();
trie.insert("apple");
trie.insert("appetizer");
console.log(trie.autocomplete("app")); // Output: ["apple", "appetizer"]
console.log(trie.autocomplete("ban")); // Output: []
Represents a sparse matrix.
Kind: global class
Constructs a sparse matrix with the specified number of rows and columns.
| Param | Type | Description |
|---|---|---|
| rows | number | The number of rows in the matrix. |
| cols | number | The number of columns in the matrix. |
Example
const matrix = new SparseMatrix(3, 4);
numberGets the value at the specified row and column in the matrix.
Kind: instance method of SparseMatrix
Returns: number - The value at the specified position, or 0 if the position is empty.
| Param | Type | Description |
|---|---|---|
| row | number | The row index (0-based). |
| col | number | The column index (0-based). |
Example
const matrix = new SparseMatrix(3, 4);
matrix.set(0, 1, 5);
console.log(matrix.get(0, 1)); // Output: 5
console.log(matrix.get(1, 2)); // Output: 0
Sets the value at the specified row and column in the matrix.
Kind: instance method of SparseMatrix
| Param | Type | Description |
|---|---|---|
| row | number | The row index (0-based). |
| col | number | The column index (0-based). |
| value | number | The value to set. |
Example
const matrix = new SparseMatrix(3, 4);
matrix.set(0, 1, 5);
console.log(matrix.get(0, 1)); // Output: 5
SparseMatrixTransposes the matrix, swapping rows and columns.
Kind: instance method of SparseMatrix
Returns: SparseMatrix - The transposed matrix.
Example
const matrix = new SparseMatrix(3, 4);
matrix.set(0, 1, 5);
const transposed = matrix.transpose();
console.log(transposed.get(1, 0)); // Output: 5
SparseMatrixAdds two matrices together and returns a new matrix with the result.
Kind: instance method of SparseMatrix
Returns: SparseMatrix - The resulting matrix after addition.
| Param | Type | Description |
|---|---|---|
| otherMatrix | SparseMatrix | The matrix to add. |
Example
const matrixA = new SparseMatrix(2, 3);
matrixA.set(0, 1, 5);
const matrixB = new SparseMatrix(2, 3);
matrixB.set(0, 1, 3);
const result = matrixA.add(matrixB);
console.log(result.get(0, 1)); // Output: 8
SparseMatrixMultiplies two matrices together and returns a new matrix with the result.
Kind: instance method of SparseMatrix
Returns: SparseMatrix - The resulting matrix after multiplication.
| Param | Type | Description |
|---|---|---|
| otherMatrix | SparseMatrix | The matrix to multiply by. |
Example
const matrixA = new SparseMatrix(2, 3);
matrixA.set(0, 1, 5);
const matrixB = new SparseMatrix(3, 2);
matrixB.set(1, 0, 3);
const result = matrixA.multiply(matrixB);
console.log(result.get(0, 0)); // Output: 15
Compresses the matrix by removing zero values.
Kind: instance method of SparseMatrix
Example
const matrix = new SparseMatrix(3, 4);
matrix.set(0, 1, 5);
matrix.set(1, 2, 0);
matrix.compress();
console.log(matrix.get(0, 1)); // Output: 5
console.log(matrix.get(1, 2)); // Output: 0
Represents a BitSet, a data structure for efficient manipulation of bits.
Kind: global class
booleannumbernumberConstructs a BitSet with the specified number of bits.
| Param | Type | Description |
|---|---|---|
| size | number | The number of bits in the BitSet. |
Example
const bitSet = new BitSet(10);
Sets the bit at the specified index to 1.
Kind: instance method of BitSet
| Param | Type | Description |
|---|---|---|
| index | number | The index of the bit to set. |
Example
const bitSet = new BitSet(10);
bitSet.set(3);
console.log(bitSet.test(3)); // Output: true
Clears the bit at the specified index (sets it to 0).
Kind: instance method of BitSet
| Param | Type | Description |
|---|---|---|
| index | number | The index of the bit to clear. |
Example
const bitSet = new BitSet(10);
bitSet.set(3);
bitSet.clear(3);
console.log(bitSet.test(3)); // Output: false
Toggles the bit at the specified index (flips its value).
Kind: instance method of BitSet
| Param | Type | Description |
|---|---|---|
| index | number | The index of the bit to toggle. |
Example
const bitSet = new BitSet(10);
bitSet.toggle(3);
console.log(bitSet.test(3)); // Output: true
bitSet.toggle(3);
console.log(bitSet.test(3)); // Output: false
booleanTests the value of the bit at the specified index.
Kind: instance method of BitSet
Returns: boolean - true if the bit is set (1), false if it is clear (0).
| Param | Type | Description |
|---|---|---|
| index | number | The index of the bit to test. |
Example
const bitSet = new BitSet(10);
bitSet.set(3);
console.log(bitSet.test(3)); // Output: true
numberCounts the number of set (1) bits in the BitSet.
Kind: instance method of BitSet
Returns: number - The count of set bits.
Example
const bitSet = new BitSet(10);
bitSet.set(3);
bitSet.set(5);
console.log(bitSet.countSetBits()); // Output: 2
numberFinds the index of the next set (1) bit starting from the specified index.
Kind: instance method of BitSet
Returns: number - The index of the next set bit, or -1 if not found.
| Param | Type | Description |
|---|---|---|
| startIndex | number | The starting index (inclusive). |
Example
const bitSet = new BitSet(10);
bitSet.set(3);
bitSet.set(5);
console.log(bitSet.findNextSetBit(0)); // Output: 3
console.log(bitSet.findNextSetBit(4)); // Output: 5
console.log(bitSet.findNextSetBit(6)); // Output: -1
Represents a Circular Buffer, a data structure for managing a fixed-size buffer with efficient enqueue and dequeue operations.
Kind: global class
TbooleanbooleanTConstructs a Circular Buffer with the specified size.
| Param | Type | Description |
|---|---|---|
| size | number | The maximum size of the buffer. |
Example
const circularBuffer = new CircularBuffer<number>(5);
Enqueues an element at the rear of the Circular Buffer.
Kind: instance method of CircularBuffer
| Param | Type | Description |
|---|---|---|
| element | T | The element to enqueue. |
Example
const circularBuffer = new CircularBuffer<number>(5);
circularBuffer.enqueue(1);
circularBuffer.enqueue(2);
TDequeues an element from the front of the Circular Buffer.
Kind: instance method of CircularBuffer
Returns: T - The dequeued element.
Example
const circularBuffer = new CircularBuffer<number>(5);
circularBuffer.enqueue(1);
const element = circularBuffer.dequeue();
console.log(element); // Output: 1
booleanChecks if the Circular Buffer is full.
Kind: instance method of CircularBuffer
Returns: boolean - true if the buffer is full, false otherwise.
Example
const circularBuffer = new CircularBuffer<number>(2);
circularBuffer.enqueue(1);
circularBuffer.enqueue(2);
console.log(circularBuffer.isFull()); // Output: true
booleanChecks if the Circular Buffer is empty.
Kind: instance method of CircularBuffer
Returns: boolean - true if the buffer is empty, false otherwise.
Example
const circularBuffer = new CircularBuffer<number>(2);
console.log(circularBuffer.isEmpty()); // Output: true
TPeeks at the element at the front of the Circular Buffer without dequeuing it.
Kind: instance method of CircularBuffer
Returns: T - The element at the front.
Example
const circularBuffer = new CircularBuffer<number>(3);
circularBuffer.enqueue(1);
circularBuffer.enqueue(2);
const element = circularBuffer.peek();
console.log(element); // Output: 1
Clears all elements from the Circular Buffer.
Kind: instance method of CircularBuffer
Example
const circularBuffer = new CircularBuffer<number>(3);
circularBuffer.enqueue(1);
circularBuffer.enqueue(2);
circularBuffer.clear();
console.log(circularBuffer.isEmpty()); // Output: true
Represents a node in a self-adjusting list (Splay Tree).
Represents a self-adjusting list (Splay Tree).
Kind: global class
Performs a splay operation on the tree to bring the specified element to the root.
Kind: instance method of SelfAdjustingList
| Param | Type | Description |
|---|---|---|
| element | T | The element to splay. |
Example
const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.splay(1);
Inserts an element into the self-adjusting list.
Kind: instance method of SelfAdjustingList
| Param | Type | Description |
|---|---|---|
| element | T | The element to insert. |
Example
const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.insert(2);
Moves the specified element to the front of the self-adjusting list.
Kind: instance method of SelfAdjustingList
| Param | Type | Description |
|---|---|---|
| element | T | The element to move to the front. |
Example
const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.insert(2);
splayTree.moveToFront(1);
Inserts an element after a specified element in the self-adjusting list.
Kind: instance method of SelfAdjustingList
| Param | Type | Description |
|---|---|---|
| target | T | The element after which to insert. |
| element | T | The element to insert. |
Example
const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.insert(3);
splayTree.insertAfter(1, 2);
This file contains all Wavefuel's async utility functions
Kind: global variable
Author: Mr.Blue
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White
This file contains all Wavefuel's file utility functions
Kind: global variable
Author: Mr.Blue
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White
This file contains all Wavefuel's test utility functions
Kind: global variable
Author: Mr.Blue
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White MrBlue
In-memory cache for storing cached API responses. You may need to adjust the cache implementation based on your needs.
Promise.<T>Sends a GET request to the specified URL and returns the response data.
Kind: global function
Returns: Promise.<T> - A Promise that resolves with the response data of type T.
Throws:
Error If an error occurs during the request.| Param | Type | Description |
|---|---|---|
| url | string | The URL to send the GET request to. |
Promise.<T>Sends a POST request to the specified URL with the provided data and returns the response data.
Kind: global function
Returns: Promise.<T> - A Promise that resolves with the response data of type T.
Throws:
Error If an error occurs during the request.| Param | Type | Description |
|---|---|---|
| url | string | The URL to send the POST request to. |
| data | Record.<string, any> | The data to send in the request body. |
Promise.<T>Sends a PUT request to the specified URL with the provided data and returns the response data.
Kind: global function
Returns: Promise.<T> - A Promise that resolves with the response data of type T.
Throws:
Error If an error occurs during the request.| Param | Type | Description |
|---|---|---|
| url | string | The URL to send the PUT request to. |
| data | Record.<string, any> | The data to send in the request body. |
Promise.<T>Sends a PATCH request to the specified URL with the provided data and returns the response data.
Kind: global function
Returns: Promise.<T> - A Promise that resolves with the response data of type T.
Throws:
Error If an error occurs during the request.| Param | Type | Description |
|---|---|---|
| url | string | The URL to send the PATCH request to. |
| data | Record.<string, any> | The data to send in the request body. |
Promise.<T>Sends a DELETE request to the specified URL and returns the response data.
Kind: global function
Returns: Promise.<T> - A Promise that resolves with the response data of type T.
Throws:
Error If an error occurs during the request.| Param | Type | Description |
|---|---|---|
| url | string | The URL to send the DELETE request to. |
Promise.<Headers>Sends a HEAD request to the specified URL and returns the response headers.
Kind: global function
Returns: Promise.<Headers> - A Promise that resolves with the response headers as a Headers object.
Throws:
Error If an error occurs during the request.| Param | Type | Description |
|---|---|---|
| url | string | The URL to send the HEAD request to. |
Promise.<T>Sends a custom HTTP request to the specified URL with the given options and returns the response data or headers.
Kind: global function
Returns: Promise.<T> - A Promise that resolves with the response data of type T or Headers if no body is expected.
Throws:
Error If an error occurs during the request.| Param | Type | Description |
|---|---|---|
| url | string | The URL to send the custom request to. |
| options | RequestInit | The options for the custom request, including method, headers, body, etc. |
Example
Sending a custom POST request with JSON body
const apiUrl = 'https://api.example.com/custom';
const customOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'value' }),
};
sendCustomRequest<{ message: string }>(apiUrl, customOptions)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
});
stringSerializes an object into a query string format for use in URL parameters.
Kind: global function
Returns: string - The serialized query string.
| Param | Type | Description |
|---|---|---|
| data | Record.<string, any> | The object to be serialized into a query string. |
Example
Serialize an object into a query string
const data = { name: 'John', age: 30 };
const queryString = serializeData(data);
console.log(queryString); // Output: "name=John&age=30"
Record.<string, any>Deserializes a query string into an object.
Kind: global function
Returns: Record.<string, any> - The deserialized object.
| Param | Type | Description |
|---|---|---|
| queryString | string | The query string to be deserialized. |
Example
Deserialize a query string into an object
const queryString = 'name=John&age=30';
const deserializedData = deserializeData(queryString);
console.log(deserializedData); // Output: { name: 'John', age: '30' }
objectConverts an XML string into a JSON object using inbuilt functions.
Kind: global function
Returns: object - The JSON object.
| Param | Type | Description |
|---|---|---|
| xmlString | string | The XML string to be converted. |
Example
Convert an XML string into a JSON object
const xmlString = '<root><name>John</name><age>30</age></root>';
const jsonObject = convertXMLToJSON(xmlString);
console.log(jsonObject); // Output: { root: { name: 'John', age: '30' } }
Array.<object>Converts a CSV string into a JSON array.
Kind: global function
Returns: Array.<object> - An array of JSON objects representing the CSV data.
| Param | Type | Description |
|---|---|---|
| csvString | string | The CSV string to be converted. |
| delimiter | string | The delimiter used in the CSV (e.g., ',' or ';'). |
Example
Convert a CSV string into a JSON array
const csvString = 'Name, Age, City\nJohn, 30, New York\nAlice, 25, Los Angeles';
const jsonArray = convertCSVToJSON(csvString, ',');
console.log(jsonArray);
Output: [
{ Name: 'John', Age: '30', City: 'New York' },
{ Name: 'Alice', Age: '25', City: 'Los Angeles' }
]
stringFormats data for display by converting it to a human-readable string or HTML.
Kind: global function
Returns: string - The formatted data as a human-readable string or HTML.
| Param | Type | Description |
|---|---|---|
| data | object | The data object to be formatted. |
Example
Format a data object for display
const data = { name: 'John', age: 30, city: 'New York' };
const formattedData = formatDataForDisplay(data);
console.log(formattedData);
Output: "Name: John\nAge: 30\nCity: New York"
Promise.<any>Handles an HTTP response, parsing the data and handling different status codes.
Kind: global function
Returns: Promise.<any> - A Promise that resolves with the parsed response data.
Throws:
Error If an error occurs during response handling.| Param | Type | Description |
|---|---|---|
| response | Response | The HTTP response object. |
Example
Handle an HTTP response and parse the data
const apiUrl = 'https://api.example.com/data';
fetch(apiUrl)
.then(handleResponse)
.then((data) => {
console.log(data); // Parsed response data
})
.catch((error) => {
console.error(error);
});
Array.<any>Paginates a list of items and returns a specific page of results.
Kind: global function
Returns: Array.<any> - The paginated page of results.
| Param | Type | Description |
|---|---|---|
| items | Array.<any> | The list of items to paginate. |
| pageNumber | number | The page number to retrieve (1-based index). |
| pageSize | number | The number of items per page. |
Example
Paginate a list of items
const itemList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const page = paginateResults(itemList, 2, 3);
console.log(page); // Output: [4, 5, 6]
string | nullGenerates a URL or link to access the next page of paginated results.
Kind: global function
Returns: string | null - The URL for the next page or null if there's no next page.
| Param | Type | Description |
|---|---|---|
| baseUrl | string | The base URL of the resource. |
| currentPage | number | The current page number (1-based index). |
| pageSize | number | The number of items per page. |
| totalItems | number | The total number of items across all pages. |
Example
Generate a link to the next page of results
const baseUrl = 'https://api.example.com/resource?page=';
const currentPage = 2;
const pageSize = 10;
const totalItems = 35;
const nextPageLink = getNextPageLink(baseUrl, currentPage, pageSize, totalItems);
console.log(nextPageLink);
Output: "https://api.example.com/resource?page=3"
string | nullGenerates a URL or link to access the previous page of paginated results.
Kind: global function
Returns: string | null - The URL for the previous page or null if there's no previous page.
| Param | Type | Description |
|---|---|---|
| baseUrl | string | The base URL of the resource. |
| currentPage | number | The current page number (1-based index). |
| pageSize | number | The number of items per page. |
Example
Generate a link to the previous page of results
const baseUrl = 'https://api.example.com/resource?page=';
const currentPage = 3;
const pageSize = 10;
const previousPageLink = getPreviousPageLink(baseUrl, currentPage, pageSize);
console.log(previousPageLink);
Output: "https://api.example.com/resource?page=2"
numberCalculates the total number of pages required to paginate a list of items.
Kind: global function
Returns: number - The total number of pages.
| Param | Type | Description |
|---|---|---|
| totalItems | number | The total number of items to paginate. |
| pageSize | number | The number of items per page. |
Example
Calculate the total number of pages for pagination
const totalItems = 35;
const pageSize = 10;
const totalPages = calculateTotalPages(totalItems, pageSize);
console.log(totalPages); // Output: 4
Promise.<void>Handles API errors by checking the response and parsing error messages.
Kind: global function
Returns: Promise.<void> - A Promise that resolves if there are no errors, or rejects with an error message.
| Param | Type | Description |
|---|---|---|
| response | Response | The HTTP response object from the API request. |
Example
Handle API errors when making a fetch request
const apiUrl = 'https://api.example.com/data';
fetch(apiUrl)
.then(handleAPIErrors)
.then((data) => {
console.log(data); // API response data
})
.catch((error) => {
console.error(error); // Handle API error
});
Promise.<void>Handles rate limit exceeded errors by implementing rate limiting logic.
Kind: global function
Returns: Promise.<void> - A Promise that resolves after waiting for the specified time.
| Param | Type | Description |
|---|---|---|
| retryAfterSeconds | number | The number of seconds to wait before retrying the request. |
Example
Handle rate limit exceeded error and retry the request
const retryAfterSeconds = 60; // Example: Retry after 1 minute
handleRateLimitExceeded(retryAfterSeconds)
.then(() => {
// Retry the API request here
console.log('Retrying the request after rate limit exceeded error.');
})
.catch((error) => {
console.error(error); // Handle error if waiting fails
});
Promise.<void>Handles timeout errors by implementing timeout logic.
Kind: global function
Returns: Promise.<void> - A Promise that resolves after waiting for the specified time.
| Param | Type | Description |
|---|---|---|
| timeoutMilliseconds | number | The maximum time to wait before triggering the timeout. |
Example
Handle timeout error and retry the operation
const timeoutMilliseconds = 5000; // Example: 5 seconds
handleTimeoutError(timeoutMilliseconds)
.then(() => {
// Handle the timeout error by retrying the operation or taking other actions.
console.log('Operation timed out.');
})
.catch((error) => {
console.error(error); // Handle error if waiting fails
});
HeadersGenerates authentication headers for HTTP Basic Authentication.
Kind: global function
Returns: Headers - Authentication headers.
| Param | Type | Description |
|---|---|---|
| username | string | The username for authentication. |
| password | string | The password for authentication. |
Example
Generate authentication headers for Basic Authentication
const username = 'myUsername';
const password = 'myPassword';
const headers = generateAuthHeaders(username, password);
Use these headers in your API request
fetch('https://api.example.com/resource', { headers })
.then((response) => {
// Handle the API response
})
.catch((error) => {
console.error(error);
});
RequestInitAuthorizes an HTTP request by adding authorization headers.
Kind: global function
Returns: RequestInit - The updated request configuration with authorization headers.
| Param | Type | Description |
|---|---|---|
| requestConfig | RequestInit | The configuration for the HTTP request. |
| authToken | string | The authorization token (e.g., bearer token). |
Example
Authorize an API request with a bearer token
const apiUrl = 'https://api.example.com/resource';
const authToken = 'Bearer myAuthToken';
const requestConfig = {
method: 'GET',
};
const authorizedConfig = authorizeRequest(requestConfig, authToken);
fetch(apiUrl, authorizedConfig)
.then((response) => {
// Handle the API response
})
.catch((error) => {
console.error(error);
});
Logs information about an API call.
Kind: global function
| Param | Type | Description |
|---|---|---|
| method | string | The HTTP method of the API call (e.g., 'GET', 'POST'). |
| url | string | The URL of the API endpoint. |
| headers | Headers | The request headers. |
| [requestBody] | string | The request body, if applicable. |
| [responseBody] | string | The response body, if applicable. |
Example
Log an API call
const apiUrl = 'https://api.example.com/resource';
const requestHeaders = new Headers({
'Authorization': 'Bearer myAuthToken',
'Content-Type': 'application/json',
});
const requestBody = JSON.stringify({ key: 'value' });
Simulate an API call and log it
const response = await fetch(apiUrl, {
method: 'POST',
headers: requestHeaders,
body: requestBody,
});
const responseBody = await response.text();
logAPICall('POST', apiUrl, requestHeaders, requestBody, responseBody);
Promise.<Response>Monitors an API call by tracking start time, end time, and response status.
Kind: global function
Returns: Promise.<Response> - A Promise that resolves with the API response.
| Param | Type | Description |
|---|---|---|
| method | string | The HTTP method of the API call (e.g., 'GET', 'POST'). |
| url | string | The URL of the API endpoint. |
| apiCallPromise | Promise.<Response> | The Promise representing the API call. |
Example
Monitor an API call
const apiUrl = 'https://api.example.com/resource';
Create a Promise representing the API call
const apiCallPromise = fetch(apiUrl, {
method: 'GET',
headers: {
'Authorization': 'Bearer myAuthToken',
},
});
Monitor the API call and log the response status
monitorAPICall('GET', apiUrl, apiCallPromise)
.then((response) => {
console.log('API call completed with status:', response.status);
})
.catch((error) => {
console.error('API call failed:', error);
});
Caches an API response using a cache key and stores it in memory.
Kind: global function
| Param | Type | Description |
|---|---|---|
| cacheKey | string | The key for caching the API response. |
| response | Response | The API response to cache. |
Response | nullRetrieves a cached API response using a cache key.
Kind: global function
Returns: Response | null - The cached API response, or null if not found.
| Param | Type | Description |
|---|---|---|
| cacheKey | string | The key for retrieving the cached API response. |
ObjectValidates and sanitizes request parameters before making an API request.
Kind: global function
Returns: Object - The sanitized request parameters.
| Param | Type | Description |
|---|---|---|
| params | Object | The request parameters object. |
Example
Validate and sanitize request parameters before making an API request
const requestParams = {
query: 'search term',
page: 1,
// Add more parameters as needed
};
const sanitizedParams = validateRequestParameters(requestParams);
Make an API request with the sanitized parameters
fetch('https://api.example.com/resource', {
method: 'GET',
// Pass sanitizedParams as query parameters or in the request body
})
.then((response) => {
// Handle the API response
})
.catch((error) => {
console.error('API request failed:', error);
});
HeadersSets the "Content-Type" header for an HTTP request.
Kind: global function
Returns: Headers - The updated headers object with the "Content-Type" header.
| Param | Type | Description |
|---|---|---|
| headers | Headers | The headers object for the request. |
| contentType | string | The content type to set (e.g., 'application/json'). |
Example
Create an HTTP request with a custom Content-Type header
const apiUrl = 'https://api.example.com/resource';
const requestData = {
key: 'value'
};
const headers = new Headers();
setRequestContentType(headers, 'application/json');
fetch(apiUrl, {
method: 'POST',
headers,
body: JSON.stringify(requestData),
})
.then((response) => {
// Handle the API response
})
.catch((error) => {
console.error('API request failed:', error);
});
ObjectMaps API data to a model or object.
Kind: global function
Returns: Object - The mapped model or object.
| Param | Type | Description |
|---|---|---|
| apiData | Object | The data received from the API response. |
Example
Map API data to a user model
const apiResponse = {
id: 1,
username: 'john_doe',
email: 'john@example.com',
// Add more properties as needed
};
const userModel = mapAPIDataToModel(apiResponse);
Now you can work with the user model in your application
console.log('User ID:', userModel.id);
console.log('Username:', userModel.username);
console.log('Email:', userModel.email);
WebSocketConnects to a WebSocket server.
Kind: global function
Returns: WebSocket - The WebSocket instance representing the connection.
| Param | Type | Description |
|---|---|---|
| url | string | The URL of the WebSocket server. |
Example
Connect to a WebSocket server
const socketUrl = 'wss://api.example.com/socket';
const socket = connectWebSocket(socketUrl);
Set up event handlers for the WebSocket
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
// You can send messages or perform other actions here
};
socket.onmessage = (event) => {
console.log('WebSocket message received:', event.data);
// Handle incoming WebSocket messages
};
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
// Handle WebSocket closure
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
// Handle WebSocket errors
};
Sends a message over a WebSocket connection.
Kind: global function
| Param | Type | Description |
|---|---|---|
| socket | WebSocket | The WebSocket instance representing the connection. |
| message | string | Blob | ArrayBuffer | The message to send. |
Example
Send a text message over a WebSocket connection
const socketUrl = 'wss://api.example.com/socket';
const socket = connectWebSocket(socketUrl);
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
// Send a text message
sendWebSocketMessage(socket, 'Hello, WebSocket!');
};
socket.onmessage = (event) => {
console.log('WebSocket message received:', event.data);
// Handle incoming WebSocket messages
};
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
// Handle WebSocket closure
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
// Handle WebSocket errors
};
Closes a WebSocket connection gracefully.
Kind: global function
| Param | Type | Default | Description |
|---|---|---|---|
| socket | WebSocket | The WebSocket instance to close. | |
| [code] | number | 1000 | A numeric status code indicating the reason for closure. |
| [reason] | string | A human-readable explanation for the closure. |
Example
Close a WebSocket connection gracefully
const socketUrl = 'wss://api.example.com/socket';
const socket = new WebSocket(socketUrl);
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
// Perform some operations, then close the connection
closeWebSocketConnection(socket, 1000, 'Connection closed gracefully');
};
socket.onmessage = (event) => {
console.log('WebSocket message received:', event.data);
// Handle incoming WebSocket messages
};
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
// Handle WebSocket closure
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
// Handle WebSocket errors
};
stringSanitizes input data to remove potentially harmful characters or validate against specific criteria.
Kind: global function
Returns: string - The sanitized input data.
| Param | Type | Description |
|---|---|---|
| input | string | The input data to sanitize. |
Example
Sanitize user-provided input
const userInput = '<script>alert("Hello, World!");</script>';
const sanitizedInput = sanitizeInput(userInput);
Use the sanitized input in your application
console.log('Sanitized input:', sanitizedInput);
Promise.<Response>Uploads a file to a remote API endpoint.
Kind: global function
Returns: Promise.<Response> - A Promise that resolves with the API response.
| Param | Type | Description |
|---|---|---|
| apiUrl | string | The URL of the API endpoint to upload the file to. |
| file | File | The File object representing the file to upload. |
Example
Upload a file to the API
const apiUrl = 'https://api.example.com/upload';
const fileInput = document.getElementById('fileInput'); // Assuming an HTML file input element.
const file = fileInput.files[0]; // Get the selected file from the input element.
if (file) {
uploadFileToAPI(apiUrl, file)
.then((response) => {
// Handle the API response after successful upload
console.log('File uploaded successfully:', response);
})
.catch((error) => {
// Handle errors during file upload
console.error('File upload failed:', error);
});
} else {
console.error('No file selected for upload.');
}
Initiates the download of a file from a remote API endpoint.
Kind: global function
| Param | Type | Description |
|---|---|---|
| apiUrl | string | The URL of the API endpoint to download the file from. |
| fileName | string | The desired name for the downloaded file. |
Example
Initiate the download of a file from the API
const apiUrl = 'https://api.example.com/download';
const fileName = 'example-file.txt'; // Specify the desired file name.
downloadFileFromAPI(apiUrl, fileName);
Promise.<Array.<Object>>Retrieves a list of nearby locations or points of interest based on a geographical coordinate.
Kind: global function
Returns: Promise.<Array.<Object>> - A Promise that resolves with an array of nearby locations.
| Param | Type | Description |
|---|---|---|
| latitude | number | The latitude of the reference location. |
| longitude | number | The longitude of the reference location. |
| radius | number | The search radius in meters from the reference location. |
| category | string | The category or type of locations to search for (e.g., 'restaurant', 'gas station'). |
numberCalculates the distance between two sets of geographical coordinates using the Haversine formula.
Kind: global function
Returns: number - The distance in meters.
| Param | Type | Description |
|---|---|---|
| lat1 | number | Latitude of the first location. |
| lon1 | number | Longitude of the first location. |
| lat2 | number | Latitude of the second location. |
| lon2 | number | Longitude of the second location. |
ObjectAuthorizes an API request with an API key by adding it to the request headers.
Kind: global function
Returns: Object - An object containing the updated headers with the API key.
| Param | Type | Description |
|---|---|---|
| apiKey | string | The API key to be added to the headers. |
| [headers] | Object | Additional HTTP headers to include in the request. |
Example
Authorize an API request with an API key
const apiKey = 'your_api_key';
const apiUrl = 'https://api.example.com/resource';
const headers = authorizeWithApiKey(apiKey);
Include the updated headers in your API request
const requestOptions = {
method: 'GET',
headers: {
...headers,
// Add any additional headers if needed
},
};
fetch(apiUrl, requestOptions)
.then((response) => {
// Handle the API response
})
.catch((error) => {
// Handle API request errors
});
Promise.<string>Refreshes an OAuth access token using a refresh token.
Kind: global function
Returns: Promise.<string> - A Promise that resolves with the new access token.
| Param | Type | Description |
|---|---|---|
| refreshToken | string | The OAuth refresh token. |
| clientId | string | The OAuth client ID. |
| clientSecret | string | The OAuth client secret. |
| tokenEndpoint | string | The OAuth token endpoint URL. |
Example
Refresh an access token using a refresh token
const refreshToken = 'your_refresh_token';
const clientId = 'your_client_id';
const clientSecret = 'your_client_secret';
const tokenEndpoint = 'https://oauth.example.com/token';
refreshAccessToken(refreshToken, clientId, clientSecret, tokenEndpoint)
.then((accessToken) => {
// Use the refreshed access token for API requests
console.log('Refreshed access token:', accessToken);
})
.catch((error) => {
// Handle errors during token refresh
console.error('Error refreshing access token:', error);
});
Promise.<any>Apply exponential backoff for retrying a network request with a maximum number of retries.
Kind: global function
Returns: Promise.<any> - A Promise that resolves with the result of the successful request or rejects after exhausting retries.
| Param | Type | Description |
|---|---|---|
| requestFn | function | A function that performs the network request and returns a Promise. |
| maxRetries | number | The maximum number of retry attempts. |
| baseDelay | number | The base delay in milliseconds before the first retry. |
Example
Example usage with a fetch request:
const apiUrl = 'https://api.example.com/resource';
function performRequest() {
return fetch(apiUrl)
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
});
}
applyExponentialBackoff(performRequest, 3, 1000)
.then((result) => {
// Handle the successful response
console.log('Success:', result);
})
.catch((error) => {
// Handle the error after retries
console.error('Error:', error);
});
numberChecks when the rate limit will reset and returns the reset timestamp.
Kind: global function
Returns: number - The timestamp (in seconds since the Unix epoch) when the rate limit will reset.
| Param | Type | Description |
|---|---|---|
| rateLimitHeader | string | The value of the 'X-RateLimit-Reset' HTTP header from the API response. |
Example
Example usage with a response containing rate limit information:
const responseHeaders = {
'X-RateLimit-Limit': '5000',
'X-RateLimit-Remaining': '4998',
'X-RateLimit-Reset': '1632796800', // Unix timestamp for the reset time
};
const resetTimestamp = checkRateLimitExpiry(responseHeaders['X-RateLimit-Reset']);
console.log('Rate limit will reset at:', new Date(resetTimestamp * 1000));
Logs an error message to the console or a logging service.
Kind: global function
| Param | Type | Default | Description |
|---|---|---|---|
| error | string | Error | The error message or Error object to be logged. | |
| [level] | string | ""error"" | The log level (e.g., "error", "warn", "info", "debug"). |
Example
Example usage to log an error message
const errorMessage = 'An error occurred while processing the request';
logError(errorMessage);
Example usage to log an Error object
try {
// Code that may throw an error
throw new Error('This is a custom error');
} catch (error) {
logError(error);
}
Promise.<any>Monitors the performance of an API call by measuring the execution time and logging it.
Kind: global function
Returns: Promise.<any> - A Promise that resolves with the API response.
| Param | Type | Description |
|---|---|---|
| apiEndpoint | string | The URL or endpoint of the API being called. |
| apiCall | function | A function that makes the API call and returns a Promise. |
Example
Example usage to monitor the performance of an API call
const apiUrl = 'https://api.example.com/resource';
async function fetchDataFromAPI() {
// Perform the API call
const response = await fetch(apiUrl);
// Monitor the API call performance
await monitorAPICallPerformance(apiUrl, async () => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
});
}
fetchDataFromAPI()
.then((result) => {
// Handle the successful API response
console.log('API Data:', result);
})
.catch((error) => {
// Handle API request errors
console.error('Error fetching data from API:', error);
});
Invalidates a cache entry by removing it from the cache.
Kind: global function
| Param | Type | Description |
|---|---|---|
| cacheKey | string | The key or identifier of the cache entry to be invalidated. |
Example
Example usage to invalidate a cache entry
const cacheKey = 'apiData:resource123';
Invalidate the cache entry
invalidateCache(cacheKey);
Clears the entire cache by removing all entries.
Kind: global function
Example
Example usage to clear the entire cache
clearCache();
Validates an API response against an expected schema.
Kind: global function
Throws:
Error Throws an error if the response does not match the expected schema.| Param | Type | Description |
|---|---|---|
| apiResponse | object | The API response object to be validated. |
| expectedSchema | object | The expected schema object. |
Example
Example usage to validate an API response
const apiResponse = {
id: 1,
name: 'John Doe',
email: 'johndoe@example.com',
};
const expectedSchema = {
id: Number,
name: String,
email: String,
};
try {
validateResponseSchema(apiResponse, expectedSchema);
console.log('API response is valid.');
} catch (error) {
console.error('API response validation failed:', error.message);
}
objectParses the 'Content-Type' header to extract the media type and charset (if present).
Kind: global function
Returns: object - An object containing the media type and charset (if present).
| Param | Type | Description |
|---|---|---|
| contentTypeHeader | string | The 'Content-Type' header value from an HTTP response. |
Example
Example usage to parse a 'Content-Type' header
const contentTypeHeader = 'application/json; charset=utf-8';
const parsedContentType = parseContentTypeHeader(contentTypeHeader);
console.log('Media Type:', parsedContentType.mediaType); // 'application/json'
console.log('Charset:', parsedContentType.charset); // 'utf-8'
stringTransforms data for export to a CSV file format.
Kind: global function
Returns: string - A CSV-formatted string representing the transformed data.
| Param | Type | Description |
|---|---|---|
| data | Array.<object> | The data to be transformed for export. |
Example
Example usage to transform data for export to CSV
const data = [
{ name: 'John', age: 30, city: 'New York' },
{ name: 'Alice', age: 25, city: 'Los Angeles' },
{ name: 'Bob', age: 35, city: 'Chicago' },
];
const csvData = transformDataForExport(data);
console.log(csvData);
Subscribes to a WebSocket topic or channel.
Kind: global function
| Param | Type | Description |
|---|---|---|
| socket | WebSocket | The WebSocket connection to subscribe with. |
| topic | string | The name or identifier of the topic or channel to subscribe to. |
| callback | function | A callback function to handle messages received on the subscribed topic. |
Example
Example usage to subscribe to a WebSocket topic
const socket = new WebSocket('wss://example.com/socket');
function handleTopicMessage(message) {
console.log('Received message on topic:', message);
// Add your custom logic to handle messages for the subscribed topic
}
subscribeToWebSocketTopic(socket, 'my-topic', handleTopicMessage);
stringEncrypts data using the AES-GCM encryption algorithm.
Kind: global function
Returns: string - The encrypted data in hexadecimal format.
| Param | Type | Description |
|---|---|---|
| data | string | The data to be encrypted. |
| encryptionKey | string | The encryption key (must be 32 bytes for AES-256-GCM). |
| iv | string | The initialization vector (IV), typically 12 bytes for AES-GCM. |
Example
Example usage to encrypt data
const dataToEncrypt = 'Sensitive information';
const encryptionKey = 'your-32-byte-secret-key';
const iv = 'your-12-byte-iv';
const encryptedData = encryptData(dataToEncrypt, encryptionKey, iv);
console.log('Encrypted Data:', encryptedData);
Promise.<void>Deletes a file on an API using an HTTP DELETE request.
Kind: global function
Returns: Promise.<void> - A promise that resolves when the file is successfully deleted.
| Param | Type | Description |
|---|---|---|
| apiUrl | string | The URL of the API endpoint that handles file deletion. |
| fileId | string | The identifier or filename of the file to be deleted. |
| authToken | string | An optional authentication token, if required by the API. |
Example
Example usage to delete a file on an API
const apiUrl = 'https://api.example.com/files';
const fileId = 'file123';
const authToken = 'your-authentication-token'; // Optional
deleteFileOnAPI(apiUrl, fileId, authToken)
.then(() => {
console.log('File deleted successfully.');
})
.catch((error) => {
console.error('File deletion failed:', error.message);
});
Promise.<string>Downloads a file from a URL and returns it as a Base64-encoded string.
Kind: global function
Returns: Promise.<string> - A promise that resolves with the Base64-encoded string of the downloaded file.
| Param | Type | Description |
|---|---|---|
| fileUrl | string | The URL of the file to be downloaded. |
Example
Example usage to download a file as Base64
const fileUrl = 'https://example.com/path/to/file.pdf';
downloadFileAsBase64(fileUrl)
.then((base64String) => {
console.log('File downloaded as Base64:', base64String);
})
.catch((error) => {
console.error('File download failed:', error.message);
});
numberCalculates the distance (in kilometers) between two geographic locations specified by their latitude and longitude using the Haversine formula.
Kind: global function
Returns: number - The distance between the two locations in kilometers.
| Param | Type | Description |
|---|---|---|
| lat1 | number | Latitude of the first location in degrees. |
| lon1 | number | Longitude of the first location in degrees. |
| lat2 | number | Latitude of the second location in degrees. |
| lon2 | number | Longitude of the second location in degrees. |
Example
Example usage to calculate the distance between two locations
const lat1 = 40.7128; // Latitude of New York City
const lon1 = -74.0060; // Longitude of New York City
const lat2 = 34.0522; // Latitude of Los Angeles
const lon2 = -118.2437; // Longitude of Los Angeles
const distance = getDistanceBetweenLocations(lat1, lon1, lat2, lon2);
console.log('Distance:', distance.toFixed(2), 'km');
anyRetrieves the element at the specified index.
Kind: global function
Returns: any - The element at the specified index.
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to retrieve the element from. |
| index | number | The index of the element to retrieve. |
Example
const myArray = [1, 2, 3, 4, 5];
const element = get(myArray, 2); // Retrieves the element at index 2 (value: 3)
console.log(element); // Output: 3
Sets the element at the specified index to a new value.
Kind: global function
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to modify. |
| index | number | The index of the element to set. |
| value | any | The new value to set at the specified index. |
Example
const myArray = [1, 2, 3, 4, 5];
set(myArray, 2, 6); // Sets the element at index 2 to 6
console.log(myArray); // Output: [1, 2, 6, 4, 5]
numberReturns the number of elements in the array.
Kind: global function
Returns: number - The number of elements in the array.
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to get the length of. |
Example
const myArray = [1, 2, 3, 4, 5];
const arrayLength = length(myArray); // Retrieves the length of the array (value: 5)
console.log(arrayLength); // Output: 5
Appends an element to the end of the array.
Kind: global function
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to push the element into. |
| element | any | The element to append to the end of the array. |
Example
const myArray = [1, 2, 3];
push(myArray, 4); // Appends the element 4 to the end of the array
console.log(myArray); // Output: [1, 2, 3, 4]
anyRemoves and returns the last element of the array.
Kind: global function
Returns: any - The last element removed from the array.
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to pop the last element from. |
Example
const myArray = [1, 2, 3];
const poppedElement = pop(myArray); // Removes and returns the last element (value: 3)
console.log(poppedElement); // Output: 3
console.log(myArray); // Output: [1, 2]
numberFinds the index of the first occurrence of a target element in the array.
Kind: global function
Returns: number - The index of the first occurrence of the target element, or -1 if not found.
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to search for the target element. |
| target | any | The element to search for. |
Example
const myArray = [1, 2, 3, 4, 5];
const index = find(myArray, 3); // Finds the index of the element 3 (value: 2)
console.log(index); // Output: 2
booleanChecks if the array contains a specific element.
Kind: global function
Returns: boolean - true if the array contains the target element, false otherwise.
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to check for the target element. |
| target | any | The element to check for. |
Example
const myArray = [1, 2, 3, 4, 5];
const containsElement = contains(myArray, 3); // Checks if the element 3 is in the array (value: true)
console.log(containsElement); // Output: true
Array.<any>Creates a shallow copy of the array.
Kind: global function
Returns: Array.<any> - A shallow copy of the input array.
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to copy. |
Example
const originalArray = [1, 2, 3];
const copiedArray = copy(originalArray); // Creates a shallow copy of the array
console.log(copiedArray); // Output: [1, 2, 3]
Removes all elements from the array.
Kind: global function
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to clear. |
Example
const myArray = [1, 2, 3, 4, 5];
clear(myArray); // Removes all elements from the array
console.log(myArray); // Output: []
Reverses the order of elements in the array.
Kind: global function
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array to reverse. |
Example
const myArray = [1, 2, 3, 4, 5];
reverse(myArray); // Reverses the order of elements in the array
console.log(myArray); // Output: [5, 4, 3, 2, 1]
Promisifies a function such that the function returns a promise.
To know more about promisification, check https://javascript.info/promisify.
To learn about how promises work check https://www.freecodecamp.org/news/guide-to-javascript-promises/#why-should-you-care-about-promises
Kind: global function
Returns: A function which returns a promise which enclosed the function sent as argument.
| Param | Description |
|---|---|
| fn | The function to be promisified |
Promisifies multiple functions.
To know more about promisification, check https://javascript.info/promisify.
To learn about how promises work check https://www.freecodecamp.org/news/guide-to-javascript-promises/#why-should-you-care-about-promises
Kind: global function
Returns: Type Object | null - An object containing function names as keys and promisified version of the respected function as its value.
| Param | Description |
|---|---|
| functions | Type Array - An array of functions to be promisified |
Creates a timeout for a promise.
To use with multiple promises, just send a promise from Promise.all to it.
To learn about how promises work check https://www.freecodecamp.org/news/guide-to-javascript-promises/#why-should-you-care-about-promises
Kind: global function
Default: 30
Returns: Type Promise - A promise which resolves when the promise sent as parameter is resolved. Rejects when promise sent in parameter is rejected or timeout function is executed.
| Param | Description |
|---|---|
| promise | Type Promise - Th promise to be timed out. |
| timeout | Type Number - Number of seconds for timeout. Default value is 30. |
Retries executing a function until it is resolved or until number of tries reaches the specified amount.
To learn about how promises work check https://www.freecodecamp.org/news/guide-to-javascript-promises/#why-should-you-care-about-promises
Kind: global function
Default: 3
Returns: - Type Promise - the result of the function, whether it is resolved or rejected.
| Param | Default | Description |
|---|---|---|
| fn | Type Function - The function to be executed | |
| tries | 3 | Type number - Number of times the function should retry running. Default value is 3. |
| ...args | Type any - parameters of the function. |
Promise.<any>Fetch data from a remote server using the specified URL.
This function makes an HTTP GET request to the provided URL and returns the response data as a JavaScript object.
Kind: global function
Returns: Promise.<any> - A Promise that resolves to the fetched data.
Throws:
Error If the HTTP request fails or the response status is not OK.| Param | Type | Description |
|---|---|---|
| url | string | The URL to fetch data from. |
| [options] | Object | Optional options for the fetch request. |
Example
Fetch data from a JSON API
const apiUrl = 'https://api.example.com/data';
try {
const data = await fetchData(apiUrl);
console.log('Fetched data:', data);
} catch (error) {
console.error('Error fetching data:', error.message);
}
Example
Fetch data with custom headers
const apiUrl = 'https://api.example.com/secure-data';
const headers = {
Authorization: 'Bearer your-access-token',
'Content-Type': 'application/json',
};
const options = {
method: 'GET',
headers,
};
try {
const data = await fetchData(apiUrl, options);
console.log('Fetched data with custom headers:', data);
} catch (error) {
console.error('Error fetching data with custom headers:', error.message);
}
Promise.<any>Fetch data from a remote server using the specified URL and return a Promise.
This function makes an HTTP GET request to the provided URL and returns a Promise that resolves to the fetched data.
Kind: global function
Returns: Promise.<any> - A Promise that resolves to the fetched data.
Throws:
Error If the HTTP request fails or the response status is not OK.| Param | Type | Description |
|---|---|---|
| url | string | The URL to fetch data from. |
Example
Fetch data from a JSON API
const apiUrl = 'https://api.example.com/data';
fetchDataPromise(apiUrl)
.then((data) => {
console.log('Fetched data:', data);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
Promise.<void>Download a file from a remote server and save it to the local file system.
This function makes an HTTP GET request to the provided URL, downloads the file, and saves it to the specified local file path.
Kind: global function
Returns: Promise.<void> - A Promise that resolves when the file is successfully downloaded and saved.
Throws:
Error If the download or file-saving process fails.| Param | Type | Description |
|---|---|---|
| url | string | The URL of the file to download. |
| localFilePath | string | The local file path where the downloaded file will be saved. |
Example
Download a file and save it locally
const fileUrl = 'https://example.com/files/sample.txt';
const localPath = './downloads/sample.txt';
try {
await downloadFile(fileUrl, localPath);
console.log('File downloaded and saved successfully.');
} catch (error) {
console.error('Error downloading or saving the file:', error.message);
}
functionDebounce user input to reduce the frequency of function execution.
This function takes an input function and returns a debounced version of it. When the debounced function is called, it will delay executing the original function until a specified delay has passed without any additional calls. This can be useful for scenarios like handling user input to improve performance by reducing the frequency of updates.
Kind: global function
Returns: function - A debounced version of the input function.
| Param | Type | Description |
|---|---|---|
| inputFunction | function | The function to debounce. |
| delay | number | The delay in milliseconds to wait before executing the debounced function. |
Example
Define a function to handle user input (e.g., search)
function handleUserInput(query) {
// Perform some action with the query
console.log('Query:', query);
}
Debounce the input function with a 300ms delay const debouncedInputFunction = debounceInput(handleUserInput, 300);
Simulate user input events debouncedInputFunction('A'); // This will not immediately trigger handleUserInput. debouncedInputFunction('Ap'); // This will also not immediately trigger handleUserInput. After a 300ms pause in input, handleUserInput('Apple') will be called once. debouncedInputFunction('Apple');
<a name="debounceSearch"></a>
## debounceSearch(searchFunction, delay) ⇒ <code>function</code>
Debounce a search function to reduce the frequency of search requests.
This function takes a search function and returns a debounced version of it. When
the debounced function is called, it will delay executing the original search
function until a specified delay has passed without any additional calls. This can
be useful for scenarios like handling user search input to reduce the frequency of
search requests to a server.
**Kind**: global function
**Returns**: <code>function</code> - A debounced version of the search function.
| Param | Type | Description |
| --- | --- | --- |
| searchFunction | <code>function</code> | The search function to debounce. |
| delay | <code>number</code> | The delay in milliseconds to wait before executing the debounced search. |
**Example**
```js
Define a function to perform a search
async function performSearch(query) {
// Perform a search and retrieve search results
console.log('Searching for:', query);
// Simulate an asynchronous search request
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log('Search results for:', query);
}
Debounce the search function with a 300ms delay
const debouncedSearch = debounceSearch(performSearch, 300);
Simulate user input events triggering the search
debouncedSearch('apple'); // This will not immediately trigger performSearch.
debouncedSearch('apples'); // This will also not immediately trigger performSearch.
After a 300ms pause in input, performSearch('applesauce') will be called once.
debouncedSearch('applesauce');
functionMemoize an asynchronous function to cache its results for given arguments.
This function takes an asynchronous function and returns a memoized version of it. The memoized function caches the results of previous calls based on the provided arguments, and if the same arguments are used in subsequent calls, it returns the cached result instead of re-computing the value.
Kind: global function
Returns: function - A memoized version of the asynchronous function.
| Param | Type | Description |
|---|---|---|
| asyncFunction | function | The asynchronous function to memoize. |
Example
Define an asynchronous function to be memoized
async function fetchDataFromServer(userId) {
// Simulate an asynchronous data fetching operation
await new Promise((resolve) => setTimeout(resolve, 1000));
return `Data for user ${userId}`;
}
Memoize the async function
const memoizedFetchData = memoizeAsyncFunction(fetchDataFromServer);
Use the memoized function with different arguments
memoizedFetchData('123')
.then((data) => {
console.log(data); // Output: "Data for user 123"
});
The result for the same argument is cached, so it's retrieved instantly
memoizedFetchData('123')
.then((data) => {
console.log(data); // Output: "Data for user 123"
});
A different argument triggers a new asynchronous call
memoizedFetchData('456')
.then((data) => {
console.log(data); // Output: "Data for user 456"
});
AsyncGenerator.<number, void, undefined>Generate asynchronous values using an async generator function.
This function creates an asynchronous generator function that yields values one by
one using the yield keyword. It allows you to produce asynchronous values in a
controlled and sequential manner.
Kind: global function
Returns: AsyncGenerator.<number, void, undefined> - An async generator that yields numbers.
| Param | Type | Description |
|---|---|---|
| count | number | The number of values to generate. |
| interval | number | The interval in milliseconds between each value. |
Example
Create an async generator that yields numbers from 1 to 5 with a 500ms interval
const generator = asyncGenerator(5, 500);
Iterate over the values using for-await-of
(async () => {
for await (const value of generator) {
console.log('Received value:', value);
}
})();
Output:
Received value: 1 (after 500ms)
Received value: 2 (after 500ms)
Received value: 3 (after 500ms)
Received value: 4 (after 500ms)
Received value: 5 (after 500ms)
Promise.<void>Consume values from an async generator and process them using a callback function.
This function takes an async generator and a callback function. It iterates over
the values produced by the generator using for-await-of and processes each value
by passing it to the provided callback function.
Kind: global function
Returns: Promise.<void> - A Promise that resolves when all values have been consumed and processed.
| Param | Type | Description |
|---|---|---|
| asyncGenerator | AsyncGenerator.<any, void, undefined> | The async generator to consume values from. |
| callback | function | The callback function to process each value. |
Example
Create an async generator that yields numbers from 1 to 3 with a 500ms interval
const generator = asyncGenerator(3, 500);
Define a callback function to process each value
function processValue(value) {
console.log('Received value:', value);
}
Consume values from the generator using the callback
consumeAsyncGenerator(generator, processValue)
.then(() => {
console.log('All values consumed.');
});
Output:
Received value: 1 (after 500ms)
Received value: 2 (after 500ms)
Received value: 3 (after 500ms)
All values consumed.
Promise.<void>Asynchronously iterate over an array and apply a function to each element.
This function takes an array and an asynchronous callback function. It iterates over each element in the array and applies the asynchronous callback function to each element in sequence, awaiting the completion of each operation before proceeding to the next.
Kind: global function
Returns: Promise.<void> - A Promise that resolves when all elements have been processed.
| Param | Type | Description |
|---|---|---|
| array | Array.<any> | The array to iterate over. |
| callback | function | The asynchronous callback function to apply to each element. |
Example
Define an array of items to process
const items = [1, 2, 3, 4, 5];
Define an asynchronous callback function to process each item
async function processItem(item) {
// Simulate an asynchronous operation
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log('Processed item:', item);
}
Use asyncForEach to process each item in the array
asyncForEach(items, processItem)
.then(() => {
console.log('All items processed.');
});
Output:
Processed item: 1 (after 1000ms)
Processed item: 2 (after 1000ms)
Processed item: 3 (after 1000ms)
Processed item: 4 (after 1000ms)
Processed item: 5 (after 1000ms)
All items processed.
Promise.<Array.<any>>Asynchronously map an array of values to a new array of transformed values.
This function takes an array and an asynchronous mapping function. It maps each element in the array to a new value by applying the asynchronous mapping function and collects the results in a new array. The resulting array contains the transformed values in the same order as the original array.
Kind: global function
Returns: Promise.<Array.<any>> - A Promise that resolves to the array of transformed values.
| Param | Type | Description |
|---|---|---|
| array | Array.<any> | The array of values to map. |
| mapper | function | The asynchronous mapping function that transforms each value. |
Example
Define an array of numbers to transform
const numbers = [1, 2, 3, 4, 5];
Define an asynchronous mapping function that doubles each number
async function doubleNumber(number) {
// Simulate an asynchronous operation
await new Promise((resolve) => setTimeout(resolve, 1000));
return number * 2;
}
Use asyncMap to transform the array of numbers
asyncMap(numbers, doubleNumber)
.then((doubledNumbers) => {
console.log('Doubled numbers:', doubledNumbers);
});
Output:
Doubled numbers: [2, 4, 6, 8, 10] (after 1000ms)
Promise.<void>Cancel an ongoing asynchronous task.
This function takes an ongoing asynchronous task represented as a Promise and attempts to cancel it. It returns a Promise that resolves when the task is successfully canceled or rejects if the task cannot be canceled.
Kind: global function
Returns: Promise.<void> - A Promise that resolves when the task is canceled.
| Param | Type | Description |
|---|---|---|
| asyncTask | Promise.<void> | The ongoing asynchronous task to cancel. |
Example
Define an asynchronous task that takes time to complete
async function performAsyncTask() {
await new Promise((resolve) => setTimeout(resolve, 5000));
console.log('Async task complete.');
}
Start the asynchronous task
const taskPromise = performAsyncTask();
After 2 seconds, attempt to cancel the task
setTimeout(async () => {
try {
await cancelAsyncTask(taskPromise);
console.log('Task canceled successfully.');
} catch (error) {
console.error('Failed to cancel task:', error.message);
}
}, 2000);
Output (after 2 seconds):
Task canceled successfully.
(After 5 seconds): Async task complete.
Promise.<number>Profile the execution time of an asynchronous function.
This function takes an asynchronous function and profiles its execution time. It measures the time it takes for the function to complete and returns a Promise that resolves with the execution time in milliseconds.
Kind: global function
Returns: Promise.<number> - A Promise that resolves with the execution time in milliseconds.
| Param | Type | Description |
|---|---|---|
| asyncFunction | function | The asynchronous function to profile. |
Example
Define an asynchronous function to profile
async function performAsyncTask() {
// Simulate an asynchronous operation
await new Promise((resolve) => setTimeout(resolve, 2000));
}
Profile the asynchronous function
profileAsyncFunction(performAsyncTask)
.then((executionTime) => {
console.log(`Async task took ${executionTime}ms to complete.`);
});
Output: Async task took 2000ms to complete.
Promise.<Object>Monitor resource usage of an asynchronous task.
This function takes an asynchronous task function and monitors its resource usage, such as CPU and memory. It returns a Promise that resolves when the task is complete and provides information about the resource usage.
Kind: global function
Returns: Promise.<Object> - A Promise that resolves with resource usage information.
| Param | Type | Description |
|---|---|---|
| asyncTask | function | The asynchronous task to monitor. |
Example
Define an asynchronous task that consumes CPU and memory
async function heavyAsyncTask() {
const array = [];
for (let i = 0; i < 1000000; i++) {
array.push(i);
}
console.log('Async task complete.');
}
Monitor the resource usage of the asynchronous task
monitorResourceUsageAsync(heavyAsyncTask)
.then((resourceUsage) => {
console.log('Resource usage:', resourceUsage);
});
Output:
Async task complete.
Resource usage: { cpuUsage: 12.34, memoryUsage: 567890 }
objectReads a JSON file from the specified path and parses it into a JavaScript object.
Kind: global function
Returns: object - - The parsed JSON data as a JavaScript object.
Throws:
Error If there is an issue reading or parsing the JSON file.| Param | Type | Description |
|---|---|---|
| path | string | The path to the JSON file to read. |
Example
Read a JSON file and retrieve its data
const data = readJson('/path/to/file.json');
console.log(data);
objectWrites JavaScript data to a JSON file at the specified path and returns the parsed JSON data.
Kind: global function
Returns: object - - The parsed JSON data as a JavaScript object.
Throws:
Error If there is an issue writing to the JSON file or parsing the JSON data.| Param | Type | Description |
|---|---|---|
| path | string | The path to the JSON file to write. |
| data | any | The JavaScript data to be written to the JSON file. |
Example
Write JavaScript data to a JSON file and retrieve its data
const data = { name: 'John', age: 30 };
const result = writeJson('/path/to/file.json', data);
console.log(result);
stringConverts an array of JSON objects into a CSV (Comma-Separated Values) string.
Kind: global function
Returns: string - - A CSV string representing the data.
| Param | Type | Description |
|---|---|---|
| data | any | An array of JSON objects to be converted to CSV. |
Example
Convert an array of JSON objects to a CSV string
const data = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
...
];
const csvString = json2Csv(data);
console.log(csvString);
Array.<Array.<any>>Removes missing values (null or undefined) from a 2D array.
Kind: global function
Returns: Array.<Array.<any>> - - The cleaned data without missing values.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data containing missing values. |
Example
const dataWithMissingValues = [
[1, 2, null],
[4, undefined, 6],
[7, 8, 9],
];
const cleanedData = removeMissingValues(dataWithMissingValues);
Result: [[7, 8, 9]]
Array.<Array.<number>>Scales numeric features in a 2D array to the [0, 1] range using Min-Max scaling.
Kind: global function
Returns: Array.<Array.<number>> - - The scaled data.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<number>> | The input data with numeric features to be scaled. |
Example
const numericData = [
[2, 4, 8],
[1, 3, 9],
[5, 7, 10],
];
const scaledData = scaleNumericFeatures(numericData);
Result: [[0.25, 0.25, 0.0], [0.0, 0.0, 1.0], [1.0, 1.0, 1.0]]
Array.<Array.<number>>One-hot encodes categorical variables in a 2D array.
Kind: global function
Returns: Array.<Array.<number>> - - The one-hot encoded data.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data containing categorical variables. |
| categoricalColumns | Array.<number> | An array of column indices containing categorical variables. |
Example
const dataWithCategorical = [
["Red", 10],
["Blue", 5],
["Green", 8],
];
const categoricalColumns = [0];
const oneHotEncodedData = oneHotEncode(dataWithCategorical, categoricalColumns);
Result: [[1, 0, 0, 10], [0, 1, 0, 5], [0, 0, 1, 8]]
Array.<Array.<number>>Normalizes numeric data using Z-Score normalization (mean = 0, std. deviation = 1).
Kind: global function
Returns: Array.<Array.<number>> - - The normalized data.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<number>> | The input data with numeric features to be normalized. |
Example
const numericData = [
[10, 20, 30],
[15, 25, 35],
[20, 30, 40],
];
const normalizedData = zScoreNormalizeData(numericData);
Result: [[-1.224744871391589, -1.224744871391589, -1.224744871391589],
[0, 0, 0],
[1.224744871391589, 1.224744871391589, 1.224744871391589]]
Array.<Array.<Array.<any>>>Splits data into training and testing sets based on a given split ratio.
Kind: global function
Returns: Array.<Array.<Array.<any>>> - - An array containing training and testing sets.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data to be split. |
| splitRatio | number | The ratio of data to be used for training (e.g., 0.8 for 80% training). |
Example
const inputData = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const splitRatio = 0.8;
const [trainingData, testingData] = splitData(inputData, splitRatio);
Result: trainingData contains 80% of the data, and testingData contains 20% of the data.
Array.<Array.<any>>Shuffles the rows of a 2D array randomly.
Kind: global function
Returns: Array.<Array.<any>> - - The shuffled data.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data to be shuffled. |
Example
const inputData = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const shuffledData = shuffleData(inputData);
Result: A random permutation of the input data rows.
Array.<Array.<any>>Data Resampling (e.g., for imbalanced datasets).
Kind: global function
Returns: Array.<Array.<any>> - - The resampled data with balanced classes.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data with a target column (binary classification). |
| targetColumn | number | The index of the target column (0-based). |
| resampleCount | number | The number of samples to create in the minority class. |
Example
const inputData = [
[1, 0],
[2, 0],
[3, 0],
[4, 1],
[5, 1],
];
const targetColumn = 1;
const resampleCount = 3;
const resampledData = resampleData(inputData, targetColumn, resampleCount);
Result: Additional samples added to the minority class (class 1).
Array.<Array.<any>>Feature Selection.
Kind: global function
Returns: Array.<Array.<any>> - - The data with selected features.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data with features. |
| selectedColumns | Array.<number> | An array of column indices to select as features. |
Example
const inputData = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const selectedColumns = [0, 2];
const selectedData = selectFeatures(inputData, selectedColumns);
Result: Data with only the selected features (columns 0 and 2).
Array.<Array.<number>>Data Transformation (e.g., log-transform for skewed data).
Kind: global function
Returns: Array.<Array.<number>> - - The transformed data (e.g., log-transformed).
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<number>> | The input data with numeric features to be transformed. |
Example
const numericData = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const logTransformedData = logTransform(numericData);
Result: Log-transformed data.
Array.<Array.<Array.<T>>>Splits data into multiple subsets for cross-validation.
Kind: global function
Returns: Array.<Array.<Array.<T>>> - - An array of data splits for cross-validation.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<T>> | The input data to be split. |
| folds | number | The number of cross-validation folds. |
Example
const inputData = [
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10],
];
const folds = 3;
const dataSplits = crossValidationSplit(inputData, folds);
Result: Array of data splits for 3-fold cross-validation.
Array.<Array.<any>>Imputes missing values (null or undefined) in a 2D array with a specified imputation value.
Kind: global function
Returns: Array.<Array.<any>> - - The data with missing values imputed using the specified value.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data containing missing values. |
| imputationValue | any | The value to use for imputing missing values. |
Example
const dataWithMissingValues = [
[1, 2, null],
[4, undefined, 6],
[7, 8, 9],
];
const imputedData = imputeMissingValues(dataWithMissingValues, 0);
Result: Missing values are replaced with 0.
Array.<Array.<number>>Creates polynomial features for a dataset.
Kind: global function
Returns: Array.<Array.<number>> - - The data with polynomial features.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<number>> | The input data with numeric features. |
| degree | number | The maximum degree of polynomial features to create. |
Example
const inputData = [
[1, 2],
[3, 4],
[5, 6],
];
const degree = 2;
const polynomialData = createPolynomialFeatures(inputData, degree);
Result: Original features and polynomial features up to degree 2.
Array.<Array.<number>>Discretizes (bins) numeric data into a specified number of bins.
Kind: global function
Returns: Array.<Array.<number>> - - The binned data.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<number>> | The input data with numeric features. |
| numBins | number | The number of bins to discretize the data into. |
Example
const numericData = [
[1.2, 3.5],
[2.5, 4.8],
[4.0, 6.1],
];
const numBins = 3;
const binnedData = binNumericData(numericData, numBins);
Result: Discretized data into 3 bins.
Array.<Array.<any>>Encodes ordinal categorical columns in a dataset using a custom encoding map.
Kind: global function
Returns: Array.<Array.<any>> - - The data with ordinal categorical columns encoded.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data containing ordinal categorical columns. |
| ordinalColumns | Array.<number> | An array of column indices containing ordinal categorical columns. |
| encodingMap | Object | A mapping of category labels to numerical values. |
Example
const dataWithOrdinal = [
['Low', 'A'],
['High', 'B'],
['Medium', 'C'],
['Low', 'A'],
];
const ordinalColumns = [0];
const encodingMap = { 'Low': 1, 'Medium': 2, 'High': 3 };
const encodedData = encodeOrdinal(dataWithOrdinal, ordinalColumns, encodingMap);
Result: Ordinal categorical column 'Low' is encoded as 1, 'Medium' as 2, 'High' as 3.
Array.<Array.<number>>Scales numeric features in a 2D array to the [0, 1] range using Min-Max scaling.
Kind: global function
Returns: Array.<Array.<number>> - - The scaled data.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<number>> | The input data with numeric features to be scaled. |
Example
const numericData = [
[2, 4, 8],
[1, 3, 9],
[5, 7, 10],
];
const scaledData = minMaxScaling(numericData);
Result: Features scaled to the [0, 1] range.
Array.<Array.<string>>Tokenizes an array of text data into words.
Kind: global function
Returns: Array.<Array.<string>> - - The tokenized data where each entry is an array of words.
| Param | Type | Description |
|---|---|---|
| textData | Array.<string> | The input text data to be tokenized. |
Example
const textData = [
'This is a sample sentence.',
'Tokenization is important.',
'NLP tasks require tokenization.',
];
const tokenizedData = textTokenization(textData);
Result: Tokenized sentences into words.
Array.<Array.<string>>Removes common stop words from an array of tokenized text data.
Kind: global function
Returns: Array.<Array.<string>> - - The text data with stop words removed.
| Param | Type | Description |
|---|---|---|
| textData | Array.<Array.<string>> | The input tokenized text data. |
Example
const tokenizedData = [
['this', 'is', 'a', 'sample', 'sentence'],
['tokenization', 'is', 'important'],
['nlp', 'tasks', 'require', 'tokenization'],
];
const dataWithoutStopWords = removeStopWords(tokenizedData);
Result: Text data with stop words removed.
Array.<Array.<string>>Stems words in an array of tokenized text data.
Kind: global function
Returns: Array.<Array.<string>> - - The text data with words stemmed.
| Param | Type | Description |
|---|---|---|
| textData | Array.<Array.<string>> | The input tokenized text data. |
Example
const tokenizedData = [
['running', 'jumps', 'played'],
['happiness', 'joyful', 'happily'],
['flies', 'flying', 'flew'],
];
const stemmedData = stemWords(tokenizedData);
Result: Text data with words stemmed.
Array.<Array.<Date>>Parses date and time strings in specified columns of a 2D array and converts them into Date objects.
Kind: global function
Returns: Array.<Array.<Date>> - - The data with date and time strings converted to Date objects.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data containing date and time strings. |
| dateTimeColumns | Array.<number> | An array of column indices containing date and time strings. |
Example
const dataWithDateTime = [
['2023-09-26', '08:30:00'],
['2023-09-27', '14:45:00'],
['2023-09-28', '10:15:00'],
];
const dateTimeColumns = [0, 1];
const parsedData = parseDateTime(dataWithDateTime, dateTimeColumns);
Result: Date and time strings converted to Date objects.
Array.<Array.<any>>Extracts time-related features from an array of Date objects.
Kind: global function
Returns: Array.<Array.<any>> - - The data with extracted time-related features.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<Date>> | The input data containing Date objects. |
Example
const dateData = [
[new Date('2023-09-26T08:30:00'), new Date('2023-09-27T14:45:00')],
[new Date('2023-09-28T10:15:00'), new Date('2023-09-29T16:30:00')],
];
const timeFeatures = extractTimeFeatures(dateData);
Result: Extracted time-related features.
Array.<Array.<number>>Removes outliers from a 2D array of numeric data based on a specified threshold.
Kind: global function
Returns: Array.<Array.<number>> - - The data with outliers removed.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<number>> | The input data with numeric features. |
| threshold | number | The threshold for outlier detection (e.g., Z-score threshold). |
Example
const numericData = [
[2, 4, 8],
[1, 3, 9],
[5, 7, 10],
];
const threshold = 2.0; // Adjust the threshold as needed
const dataWithoutOutliers = removeOutliers(numericData, threshold);
Result: Data with outliers removed based on the threshold.
Array.<Array.<any>>Encodes nominal categorical columns in a dataset using one-hot encoding.
Kind: global function
Returns: Array.<Array.<any>> - - The data with nominal categorical columns encoded using one-hot encoding.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<any>> | The input data containing nominal categorical columns. |
| nominalColumns | Array.<number> | An array of column indices containing nominal categorical columns. |
Example
const dataWithNominal = [
['Red', 'A'],
['Blue', 'B'],
['Green', 'A'],
['Red', 'C'],
];
const nominalColumns = [0, 1];
const encodedData = encodeNominal(dataWithNominal, nominalColumns);
Result: Nominal categorical columns encoded using one-hot encoding.
Array.<Array.<number>>Standardizes numeric features in a 2D array by subtracting the mean and dividing by the standard deviation.
Kind: global function
Returns: Array.<Array.<number>> - - The standardized data.
| Param | Type | Description |
|---|---|---|
| data | Array.<Array.<number>> | The input data with numeric features to be standardized. |
Example
const numericData = [
[2, 4, 8],
[1, 3, 9],
[5, 7, 10],
];
const standardizedData = standardizeData(numericData);
Result: Standardized features.
Array.<MyImageData>Augments an array of image data by applying specified transformations, such as rotation and flipping.
Kind: global function
Returns: Array.<MyImageData> - An array of augmented image data.
Throws:
Error If the canvas context is not available.| Param | Type | Description |
|---|---|---|
| images | Array.<MyImageData> | An array of image data to be augmented. |
| augmentationOptions | AugmentationOptions | Options for augmenting the images. |
Example
Define an array of image data
const imageArray = /* MyImageData array * /;
Define augmentation options
const options = {
rotate: 90, // Rotate images by 90 degrees (clockwise)
flipHorizontal: true, // Flip images horizontally
flipVertical: false // Do not flip images vertically
};
Augment the image data
const augmentedImages = augmentImageData(imageArray, options);
console.log(augmentedImages); // Output: An array of augmented image data.
Promise.<Array.<Data>>Loads data from a CSV file and returns it as an array of Data objects.
Kind: global function
Returns: Promise.<Array.<Data>> - A Promise that resolves with an array of Data objects.
Throws:
Error If there is an error reading or parsing the CSV file.| Param | Type | Description |
|---|---|---|
| filename | string | The path to the CSV file to load. |
Example
Example usage:
loadCSV('data.csv')
.then((data) => {
// Process the loaded data
console.log(data);
})
.catch((error) => {
console.error('Error loading CSV:', error);
});
Array.<Data>Filters an array of Data objects based on a custom condition.
Kind: global function
Returns: Array.<Data> - An array of Data objects that meet the filter condition.
| Param | Type | Description |
|---|---|---|
| data | Array.<Data> | The array of Data objects to filter. |
| filterFn | function | The filtering function that returns true to include an item. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 35 },
];
const filteredData = filterData(data, (item) => item.age > 30);
console.log(filteredData); // Output: [{ id: 3, name: 'Charlie', age: 35 }]
Array.<Data>Maps an array of Data objects to a new array using a custom mapping function.
Kind: global function
Returns: Array.<Data> - An array of Data objects resulting from applying the mapping function.
| Param | Type | Description |
|---|---|---|
| data | Array.<Data> | The array of Data objects to map. |
| mapFn | function | The mapping function that transforms each item. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 35 },
];
const mappedData = mapData(data, (item) => ({ ...item, age: item.age + 1 }));
console.log(mappedData);
Output:
[
{ id: 1, name: 'Alice', age: 31 },
{ id: 2, name: 'Bob', age: 26 },
{ id: 3, name: 'Charlie', age: 36 },
]
Array.<Data>Sorts an array of Data objects based on a specified key in ascending or descending order.
Kind: global function
Returns: Array.<Data> - A new array of Data objects sorted based on the specified key.
| Param | Type | Default | Description |
|---|---|---|---|
| data | Array.<Data> | The array of Data objects to sort. | |
| key | string | The key by which to sort the objects. | |
| [ascending] | boolean | true | Whether to sort in ascending order (default) or descending order. |
Example
Example usage:
const data = [
{ id: 3, name: 'Charlie', age: 35 },
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
];
const sortedDataAsc = sortData(data, 'age');
console.log(sortedDataAsc);
Output: [{ id: 2, name: 'Bob', age: 25 }, { id: 1, name: 'Alice', age: 30 }, { id: 3, name: 'Charlie', age: 35 }]
const sortedDataDesc = sortData(data, 'name', false);
console.log(sortedDataDesc);
Output: [{ id: 3, name: 'Charlie', age: 35 }, { id: 1, name: 'Alice', age: 30 }, { id: 2, name: 'Bob', age: 25 }]
Map.<string, Array.<Data>>Groups an array of Data objects by a specified key and returns a Map of grouped Data arrays.
Kind: global function
Returns: Map.<string, Array.<Data>> - A Map where keys are unique values of the specified key and values are arrays of grouped Data objects.
| Param | Type | Description |
|---|---|---|
| data | Array.<Data> | The array of Data objects to group. |
| key | string | The key by which to group the objects. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 30 },
];
const groupedData = groupBy(data, 'age');
console.log(groupedData.get('25'));
Output: [{ id: 2, name: 'Bob', age: 25 }]
console.log(groupedData.get('30'));
Output: [{ id: 1, name: 'Alice', age: 30 }, { id: 3, name: 'Charlie', age: 30 }]
Map.<string, any>Aggregates and summarizes data from an array of Data objects based on a specified grouping key and aggregation function.
Kind: global function
Returns: Map.<string, any> - A Map where keys are unique values of the specified group key, and values are the results of aggregation for each group.
| Param | Type | Description |
|---|---|---|
| data | Array.<Data> | The array of Data objects to aggregate. |
| groupKey | string | The key by which to group the data. |
| aggregationFn | function | The aggregation function that summarizes grouped data. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 30 },
];
Aggregation function to calculate the average age in each group
const averageAgeAggregation (groupedData) => {
const totalAge = groupedData.reduce((sum, item) => sum + item.age, 0);
return totalAge / groupedData.length;
};
const aggregatedData = aggregate(data, 'age', averageAgeAggregation);
console.log(aggregatedData.get('25'));
Output: 25
console.log(aggregatedData.get('30'));
Output: 30
Exports an array of data to a CSV file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| data | Array.<Data> | An array of data to export. |
| filename | string | The name of the CSV file. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 35 },
];
exportCSV(data, 'exported_data.csv');
Array.<number>Normalizes an array of numeric data using min-max scaling.
Kind: global function
Returns: Array.<number> - The normalized data.
| Param | Type | Description |
|---|---|---|
| data | Array.<number> | An array of numeric data to normalize. |
Example
Example usage:
const data = [10, 20, 30, 40, 50];
const normalizedData = minMaxNormalizeData(data);
console.log(normalizedData);
Output: [0, 0.25, 0.5, 0.75, 1]
numberCounts the number of words in a text string.
Kind: global function
Returns: number - The number of words in the text.
| Param | Type | Description |
|---|---|---|
| text | string | The input text. |
Example
Example usage:
const text = "This is an example sentence.";
const wordCount = countWords(text);
console.log(wordCount);
Output: 5
Array.<string>Finds and returns an array of keywords present in a text string.
Kind: global function
Returns: Array.<string> - An array of keywords found in the text.
| Param | Type | Description |
|---|---|---|
| text | string | The input text. |
| keywords | Array.<string> | An array of keywords to search for. |
Example
Example usage:
const text = "This is a sample text containing keywords like JavaScript and TypeScript.";
const keywords = ["JavaScript", "TypeScript", "sample"];
const foundKeywords = findKeywords(text, keywords);
console.log(foundKeywords);
Output: ["JavaScript", "TypeScript", "sample"]
stringFormat a date object into a custom string format.
This function takes a JavaScript Date object and formats it into a custom string
format according to the specified pattern.
Kind: global function
Returns: string - A string representing the formatted date.
| Param | Type | Description |
|---|---|---|
| date | Date | The date object to format. |
| pattern | string | The format pattern. Use 'YYYY' for year, 'MM' for month, 'DD' for day, 'hh' for hours, 'mm' for minutes, 'ss' for seconds, and 'SSS' for milliseconds. |
Example
Create a Date object representing September 26, 2023, 14:30:15
const date = new Date(2023, 8, 26, 14, 30, 15);
Format the date using a custom pattern
const formattedDate = format_date(date, 'YYYY-MM-DD hh:mm:ss.SSS');
console.log('Formatted date:', formattedDate);
Output: Formatted date: 2023-09-26 14:30:15.000
stringConvert a number into a human-readable format with units (e.g., KB, MB, GB).
This function takes a number representing a size in bytes and converts it into a human-readable format with appropriate units (e.g., KB, MB, GB) to make it more readable and user-friendly. It rounds the size to two decimal places and includes the unit abbreviation.
Kind: global function
Returns: string - A string representing the human-readable size with units.
Throws:
Error If the input size is negative.Remarks: This function uses the International System of Units (SI) binary prefixes, where:
| Param | Type | Description |
|---|---|---|
| sizeInBytes | number | The size in bytes to convert to human-readable format. |
Example
Convert a size in bytes to human-readable format
const sizeInBytes = 123456789; // 123,456,789 bytes
const humanReadableSize = to_human_readable(sizeInBytes);
console.log('Human-readable size:', humanReadableSize);
Output: Human-readable size: 117.74 MB
Date | nullParse a date string into a JavaScript Date object.
This function takes a date string in a specified format and parses it into a
JavaScript Date object. It supports custom date formats using placeholders:
Kind: global function
Returns: Date | null - A Date object representing the parsed date, or null if parsing fails.
Remarks: - The function returns null if parsing fails due to an invalid date string or format.
| Param | Type | Description |
|---|---|---|
| dateString | string | The date string to parse. |
| format | string | The format of the date string using placeholders. |
Example
Parse a date string in 'YYYY-MM-DD' format
const dateString = '2023-09-26';
const format = 'YYYY-MM-DD';
const parsedDate = parse_date(dateString, format);
if (parsedDate !== null) {
console.log('Parsed date:', parsedDate.toLocaleDateString());
} else {
console.error('Invalid date format.');
}
Output: Parsed date: 9/26/2023 (the actual format may vary depending on locale)
Date | nullParse an ISO 8601 date string into a JavaScript Date object.
This function takes an ISO 8601 date string and parses it into a JavaScript Date object.
It supports various ISO 8601 formats, including date-only, date-time with timezone, and more.
Kind: global function
Returns: Date | null - A Date object representing the parsed date, or null if parsing fails.
Remarks: - The function returns null if parsing fails due to an invalid ISO 8601 date string.
| Param | Type | Description |
|---|---|---|
| iso8601String | string | The ISO 8601 date string to parse. |
Example
Parse an ISO 8601 date string
const iso8601String = '2023-09-26T14:30:15Z';
const parsedDate = parse_iso8601(iso8601String);
if (parsedDate !== null) {
console.log('Parsed date:', parsedDate.toLocaleString());
} else {
console.error('Invalid ISO 8601 date format.');
}
Output: Parsed date: 9/26/2023, 2:30:15 PM (the actual format may vary depending on locale)
numberCompare two JavaScript Date objects to determine their chronological order.
This function compares two Date objects and returns an integer value indicating their chronological order:
date1 is earlier than date2, it returns a negative value.date1 is later than date2, it returns a positive value.Kind: global function
Returns: number - An integer indicating the chronological order of the dates.
Remarks: - The function returns a negative value if date1 is earlier than date2, a positive
value if date1 is later than date2, and 0 if they are equal.
| Param | Type | Description |
|---|---|---|
| date1 | Date | The first Date object to compare. |
| date2 | Date | The second Date object to compare. |
Example
Compare two Date objects
const date1 = new Date(2023, 8, 26);
const date2 = new Date(2023, 8, 27);
const result = compare_dates(date1, date2);
if (result < 0) {
console.log('date1 is earlier than date2.');
} else if (result > 0) {
console.log('date1 is later than date2.');
} else {
console.log('date1 and date2 are equal.');
}
Output: date1 is earlier than date2.
booleanCheck if a JavaScript Date object represents a date and time in the past.
This function takes a Date object and checks whether it represents a date and time that has already occurred (i.e., is in the past) when compared to the current date and time.
Kind: global function
Returns: boolean - True if the date is in the past, false if it is in the present or future.
Remarks: - The function considers the current date and time when determining if the provided date
is in the past.
true if the provided date is earlier than the current date and time; otherwise,
it returns false.| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to check. |
Example
Check if a Date object represents a past date
const pastDate = new Date(2020, 0, 1); // January 1, 2020
const isPast = is_past(pastDate);
if (isPast) {
console.log('The date is in the past.');
} else {
console.log('The date is in the present or future.');
}
Output: The date is in the past.
booleanCheck if a JavaScript Date object represents a date and time in the future.
This function takes a Date object and checks whether it represents a date and time that is in the future (i.e., has not occurred yet) when compared to the current date and time.
Kind: global function
Returns: boolean - True if the date is in the future, false if it is in the present or past.
Remarks: - The function considers the current date and time when determining if the provided date
is in the future.
true if the provided date is later than the current date and time; otherwise,
it returns false.| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to check. |
Example
Check if a Date object represents a future date
const futureDate = new Date(2030, 0, 1); // January 1, 2030
const isFuture = is_future(futureDate);
if (isFuture) {
console.log('The date is in the future.');
} else {
console.log('The date is in the present or past.');
}
Output: The date is in the future.
DateAdd a specified number of days to a JavaScript Date object.
This function takes a JavaScript Date object and adds a specified number of days to it. The result is a new Date object representing the date and time after adding the days.
Kind: global function
Returns: Date - A new Date object representing the date and time after adding the specified days.
Remarks: - The function supports adding both positive and negative values for days, allowing you
to move both into the future and the past.
| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to which days will be added. |
| daysToAdd | number | The number of days to add. Positive values add days to the future, and negative values subtract days from the past. |
Example
Add 7 days to a Date object
const currentDate = new Date(); // Current date and time
const futureDate = add_days(currentDate, 7);
console.log('Current date:', currentDate.toLocaleDateString());
console.log('Future date:', futureDate.toLocaleDateString());
Output example:
Current date: 9/26/2023 (the actual format may vary depending on locale)
Future date: 10/3/2023 (the actual format may vary depending on locale)
DateSubtract a specified number of days from a JavaScript Date object.
This function takes a JavaScript Date object and subtracts a specified number of days from it. The result is a new Date object representing the date and time after subtracting the days.
Kind: global function
Returns: Date - A new Date object representing the date and time after subtracting the specified days.
Remarks: - The function supports subtracting both positive and negative values for days, allowing you
to move both into the past and the future.
| Param | Type | Description |
|---|---|---|
| date | Date | The Date object from which days will be subtracted. |
| daysToSubtract | number | The number of days to subtract. Positive values subtract days from the past, and negative values add days to the future. |
Example
Subtract 7 days from a Date object
const currentDate = new Date(); // Current date and time
const pastDate = subtract_days(currentDate, 7);
console.log('Current date:', currentDate.toLocaleDateString());
console.log('Past date:', pastDate.toLocaleDateString());
Output example:
Current date: 9/26/2023 (the actual format may vary depending on locale)
Past date: 9/19/2023 (the actual format may vary depending on locale)
numberCalculate the number of days between two JavaScript Date objects.
This function takes two JavaScript Date objects and calculates the number of days between them, considering their date and time.
Kind: global function
Returns: number - The number of days between the two dates. A positive value indicates
that endDate is later than startDate, a negative value indicates
that endDate is earlier, and 0 indicates both dates are the same.
Remarks: - The function considers both date and time when calculating the difference between dates.
endDate is later than startDate.endDate is earlier than startDate.| Param | Type | Description |
|---|---|---|
| startDate | Date | The starting Date object. |
| endDate | Date | The ending Date object. |
Example
Calculate the number of days between two dates
const date1 = new Date(2023, 8, 26); // September 26, 2023
const date2 = new Date(2023, 9, 3); // October 3, 2023
const daysBetween = days_between_dates(date1, date2);
console.log('Days between:', daysBetween);
Output: Days between: 7
booleanCheck if a JavaScript Date object represents a valid date and time.
This function takes a JavaScript Date object and checks whether it represents a valid date and time. It considers factors such as leap years, valid months, and valid day values.
Kind: global function
Returns: boolean - True if the date is valid, false if it is not valid.
Remarks: - The function checks if the provided date is valid based on JavaScript's Date object rules,
including leap years and valid month and day values.
true if the date is valid, and false if it is not.| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to check. |
Example
Check if a Date object represents a valid date and time
const validDate = new Date(2023, 1, 28); // February 28, 2023
const invalidDate = new Date(2023, 1, 29); // February 29, 2023 (not a leap year)
const isValid1 = is_valid_date(validDate);
const isValid2 = is_valid_date(invalidDate);
console.log('IsValid1:', isValid1); // Output: IsValid1: true
console.log('IsValid2:', isValid2); // Output: IsValid2: false
booleanCheck if a year is a leap year.
This function takes a year as input and checks whether it is a leap year according to the rules of the Gregorian calendar.
Kind: global function
Returns: boolean - True if the year is a leap year, false otherwise.
Remarks: - The function checks if the provided year is a leap year according to the rules
of the Gregorian calendar.
true if the year is a leap year, and false otherwise.| Param | Type | Description |
|---|---|---|
| year | number | The year to check for leap year status. |
Example
Check if a year is a leap year
const leapYear = 2024;
const nonLeapYear = 2023;
const isLeap1 = is_leap_year(leapYear);
const isLeap2 = is_leap_year(nonLeapYear);
console.log('IsLeap1:', isLeap1); // Output: IsLeap1: true
console.log('IsLeap2:', isLeap2); // Output: IsLeap2: false
Array.<Date>Generate an array of Date objects within a specified date range.
This function takes a start date, an end date, and an optional step interval (in days) and generates an array of Date objects that fall within the specified date range.
Kind: global function
Returns: Array.<Date> - An array of Date objects representing the dates within the specified range.
Remarks: - The function generates an array of Date objects starting from startDate up to and including endDate.
step parameter allows you to specify the interval between dates in days.startDate and endDate if they are within the specified range.| Param | Type | Default | Description |
|---|---|---|---|
| startDate | Date | The start date of the range (inclusive). | |
| endDate | Date | The end date of the range (inclusive). | |
| [step] | number | 1 | Optional step interval in days (default is 1 day). |
Example
Generate an array of dates within a range
const start = new Date(2023, 8, 1); // September 1, 2023
const end = new Date(2023, 8, 5); // September 5, 2023
const dateRange = generate_date_range(start, end);
dateRange.forEach(date => {
console.log(date.toLocaleDateString());
});
Output example:
9/1/2023
9/2/2023
9/3/2023
9/4/2023
9/5/2023
Array.<Date>Generate an array of Date objects representing months within a specified date range.
This function takes a start date and an end date and generates an array of Date objects representing the first day of each month within the specified date range.
Kind: global function
Returns: Array.<Date> - An array of Date objects representing the first day of each month
within the specified range.
Remarks: - The function generates an array of Date objects representing the first day of each month
within the specified date range.
startDate and endDate are included in the generated array if they fall within the
specified range.| Param | Type | Description |
|---|---|---|
| startDate | Date | The start date of the range (inclusive). |
| endDate | Date | The end date of the range (inclusive). |
Example
Generate an array of months within a range
const start = new Date(2023, 0, 15); // January 15, 2023
const end = new Date(2023, 3, 10); // April 10, 2023
const monthRange = generate_month_range(start, end);
monthRange.forEach(month => {
console.log(month.toLocaleDateString(undefined, { year: 'numeric', month: 'long' }));
});
Output example:
January 2023
February 2023
March 2023
April 2023
numberConvert a JavaScript Date object to a Unix timestamp.
This function takes a JavaScript Date object and converts it to a Unix timestamp, which is the number of seconds that have elapsed since January 1, 1970 (UTC).
Kind: global function
Returns: number - The Unix timestamp representing the given date.
Remarks: - The Unix timestamp is the number of seconds that have passed since January 1, 1970 (UTC).
| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to convert to a Unix timestamp. |
Example
Convert a Date object to a Unix timestamp
const someDate = new Date(2023, 8, 26, 12, 0, 0); // September 26, 2023, 12:00:00 PM
const timestamp = date_to_unix_timestamp(someDate);
console.log('Unix timestamp:', timestamp);
Output example:
Unix timestamp: 1691059200
DateConvert a Unix timestamp to a JavaScript Date object.
This function takes a Unix timestamp, which is the number of seconds that have elapsed since January 1, 1970 (UTC), and converts it to a JavaScript Date object.
Kind: global function
Returns: Date - A JavaScript Date object representing the date and time corresponding to the
provided Unix timestamp.
Remarks: - The Unix timestamp is the number of seconds that have passed since January 1, 1970 (UTC).
| Param | Type | Description |
|---|---|---|
| timestamp | number | The Unix timestamp to convert to a Date object. |
Example
Convert a Unix timestamp to a Date object
const unixTimestamp = 1691059200; // September 26, 2023, 12:00:00 PM
const date = unix_timestamp_to_date(unixTimestamp);
console.log('Date:', date.toLocaleString());
Output example:
Date: 9/26/2023, 12:00:00 PM (the actual format may vary depending on locale)
stringGet the day of the week for a JavaScript Date object.
This function takes a JavaScript Date object and returns the name of the day of the week for that date.
Kind: global function
Returns: string - The name of the day of the week (e.g., "Sunday", "Monday").
Remarks: - The function returns the name of the day of the week for the provided Date object.
| Param | Type | Description |
|---|---|---|
| date | Date | The Date object for which to get the day of the week. |
Example
Get the day of the week for a Date object
const someDate = new Date(2023, 8, 26); // September 26, 2023
const dayOfWeek = get_day_of_week(someDate);
console.log('Day of the week:', dayOfWeek);
Output example:
Day of the week: Tuesday
booleanCheck if a JavaScript Date object falls on a weekend.
This function takes a JavaScript Date object and checks whether it falls on a weekend, which includes Saturday and Sunday.
Kind: global function
Returns: boolean - True if the date falls on a weekend (Saturday or Sunday), false otherwise.
Remarks: - The function checks if the provided Date object falls on a weekend, including Saturday and Sunday.
true if the date is a weekend day and false if it is a weekday.| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to check. |
Example
Check if a Date object falls on a weekend
const weekendDate = new Date(2023, 8, 30); // September 30, 2023 (Saturday)
const weekdayDate = new Date(2023, 8, 26); // September 26, 2023 (Tuesday)
const isWeekend1 = is_weekend(weekendDate);
const isWeekend2 = is_weekend(weekdayDate);
console.log('IsWeekend1:', isWeekend1); // Output: IsWeekend1: true
console.log('IsWeekend2:', isWeekend2); // Output: IsWeekend2: false
DateAdd a specified number of business days to a JavaScript Date object.
This function takes a JavaScript Date object and adds a specified number of business days to it, skipping weekends (Saturday and Sunday) as non-business days.
Kind: global function
Returns: Date - A new Date object representing the date after adding the specified business days.
Remarks: - Business days are considered to be Monday through Friday, excluding weekends (Saturday and Sunday).
| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to which business days will be added. |
| daysToAdd | number | The number of business days to add. |
Example
Add 5 business days to a Date object
const startDate = new Date(2023, 8, 26); // September 26, 2023 (Monday)
const endDate = add_business_days(startDate, 5);
console.log('Start date:', startDate.toLocaleDateString());
console.log('End date:', endDate.toLocaleDateString());
Output example:
Start date: 9/26/2023
End date: 10/3/2023
DateGet the next business day after a JavaScript Date object.
This function takes a JavaScript Date object and returns the next business day after the given date, skipping weekends (Saturday and Sunday) as non-business days.
Kind: global function
Returns: Date - A new Date object representing the next business day.
Remarks: - Business days are considered to be Monday through Friday, excluding weekends (Saturday and Sunday).
| Param | Type | Description |
|---|---|---|
| date | Date | The Date object for which to find the next business day. |
Example
Get the next business day after a Date object
const someDate = new Date(2023, 8, 28); // September 28, 2023 (Wednesday)
const nextBusinessDay = next_business_day(someDate);
console.log('Next business day:', nextBusinessDay.toLocaleDateString());
Output example:
Next business day: 9/29/2023
DateConvert a JavaScript Date object to a different time zone.
This function takes a JavaScript Date object and converts it to a new Date object representing the same date and time in a different time zone.
Kind: global function
Returns: Date - A new Date object representing the same date and time in the target time zone.
Remarks: - The function converts the provided Date object to a new Date object representing the same date and time
in the specified target time zone.
targetTimeZone parameter should be provided in the IANA Time Zone format (e.g., "America/New_York").| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to convert. |
| targetTimeZone | string | The target time zone in IANA Time Zone format (e.g., "America/New_York"). |
Example
Convert a Date object to a different time zone
const someDate = new Date(2023, 0, 15, 12, 0, 0); // January 15, 2023, 12:00:00 PM
const newYorkTimeZone = "America/New_York";
const newYorkDate = convert_timezone(someDate, newYorkTimeZone);
console.log('Original Date:', someDate.toLocaleString());
console.log('New York Date:', newYorkDate.toLocaleString());
Output example:
Original Date: 1/15/2023, 12:00:00 PM (the actual format may vary depending on locale)
New York Date: 1/15/2023, 7:00:00 AM (the actual format may vary depending on locale)
numberCalculate the age based on a birthdate and a reference date.
This function takes a birthdate and a reference date (usually the current date) and calculates the age in years between the two dates.
Kind: global function
Returns: number - The calculated age in years.
Remarks: - The function calculates the age in years by subtracting the birthdate from the reference date.
| Param | Type | Description |
|---|---|---|
| birthdate | Date | The Date object representing the birthdate. |
| referenceDate | Date | The reference Date object for age calculation (e.g., current date). |
Example
Calculate the age based on birthdate and reference date
const birthdate = new Date(1990, 8, 15); // September 15, 1990
const currentDate = new Date(); // Current date
const age = calculate_age(birthdate, currentDate);
console.log('Age:', age); // Output: Age: (calculated age based on current date)
DateGenerates a random date within a specified date range.
Kind: global function
Returns: Date - A random date within the specified range.
| Param | Type | Description |
|---|---|---|
| startDate | Date | The start date of the date range. |
| endDate | Date | The end date of the date range. |
Example
Generate a random date within a specific year (2023).
const startDate = new Date('2023-01-01');
const endDate = new Date('2023-12-31');
const randomDate = randomDate(startDate, endDate);
console.log(randomDate.toDateString()); // Output: A random date within the specified range.
DateGenerates a random date within a specified date range, with weights assigned to each day. The probability of selecting a date is proportional to its assigned weight.
Kind: global function
Returns: Date - A random date within the specified range, with weights taken into account.
| Param | Type | Description |
|---|---|---|
| startDate | Date | The start date of the date range. |
| endDate | Date | The end date of the date range. |
| weightedDays | Record.<number, number> | An object mapping days of the week (0 for Sunday, 1 for Monday, etc.) to their respective weights. |
Example
Generate a random date within a week, with higher weights for weekend days.
const startDate = new Date('2023-09-26');
const endDate = new Date('2023-10-02');
const weightedDays = { 0: 1, 1: 2, 2: 2, 3: 1, 4: 1, 5: 3, 6: 3 }; // Higher weights for Saturday and Sunday
const randomDate = weightedRandomDate(startDate, endDate, weightedDays);
console.log(randomDate.toDateString()); // Output: A random date within the specified range, with weights considered.
DateShifts a given date by a specified number of days and returns the shifted date.
Kind: global function
Returns: Date - The shifted date.
| Param | Type | Description |
|---|---|---|
| date | Date | The input date to shift. |
| daysToShift | number | The number of days to shift the date (positive or negative). |
Example
Shift a date 5 days into the future
const originalDate = new Date('2023-09-26');
const shiftedDate = shiftDate(originalDate, 5);
console.log(shiftedDate.toDateString()); // Output: "Sat Oct 01 2023"
Shift a date 2 days into the past
const anotherDate = new Date('2023-09-26');
const anotherShiftedDate = shiftDate(anotherDate, -2);
console.log(anotherShiftedDate.toDateString()); // Output: "Mon Sep 24 2023"
stringFormats the difference between two dates in a human-readable string.
Kind: global function
Returns: string - A human-readable string representing the difference between the two dates.
| Param | Type | Description |
|---|---|---|
| startDate | Date | The start date. |
| endDate | Date | The end date. |
Example
const today = new Date();
const futureDate = new Date(today);
futureDate.setDate(today.getDate() + 7); // 7 days in the future
const differenceString = formatDateDifference(today, futureDate);
console.log(differenceString); // Output: "1 week from now"
const pastDate = new Date(today);
pastDate.setDate(today.getDate() - 3); // 3 days in the past
const anotherDifferenceString = formatDateDifference(pastDate, today);
console.log(anotherDifferenceString); // Output: "3 days ago"
DateAdjusts a given date to the specified timezone offset and returns the adjusted date.
Kind: global function
Returns: Date - The adjusted date with the new timezone offset.
| Param | Type | Description |
|---|---|---|
| date | Date | The input date to adjust. |
| timezoneOffset | number | The desired timezone offset in minutes (positive or negative). |
Example
Adjust a date for a timezone offset of +120 minutes (2 hours ahead)
const originalDate = new Date('2023-09-26T12:00:00Z');
const adjustedDate = adjustForTimezoneOffset(originalDate, 120);
console.log(adjustedDate); // Output: 2023-09-26T14:00:00.000Z
Adjust a date for a timezone offset of -180 minutes (3 hours behind)
const anotherDate = new Date('2023-09-26T12:00:00Z');
const anotherAdjustedDate = adjustForTimezoneOffset(anotherDate, -180);
console.log(anotherAdjustedDate); // Output: 2023-09-26T09:00:00.000Z
numberGet the week number for a JavaScript Date object.
This function takes a JavaScript Date object and returns the week number to which the date belongs, based on a specified week numbering system (ISO 8601 or US).
Kind: global function
Returns: number - The week number to which the date belongs.
Remarks: - The function calculates the week number based on the year, month, and day of the provided Date object.
| Param | Type | Default | Description |
|---|---|---|---|
| date | Date | The Date object for which to get the week number. | |
| [weekNumberingSystem] | "iso" | "us" | "iso" | The week numbering system to use (default is ISO 8601). |
Example
Get the ISO week number for a Date object
const someDate = new Date(2023, 5, 15); // June 15, 2023
const isoWeekNumber = get_week_number(someDate, "iso");
console.log('ISO Week Number:', isoWeekNumber); // Output: ISO Week Number: 24
Get the US week number for the same Date object
const usWeekNumber = get_week_number(someDate, "us");
console.log('US Week Number:', usWeekNumber); // Output: US Week Number: 25
Date | nullDeserialize a string representation into a JavaScript Date object.
This function takes a string representation of a date and deserializes it into a JavaScript Date object based on a specified format pattern.
Kind: global function
Returns: Date | null - The JavaScript Date object representing the deserialized date,
or null if the deserialization fails.
Remarks: - The function allows you to deserialize a string representation of a date into a Date object
using a specified format pattern with format placeholders.
| Param | Type | Description |
|---|---|---|
| serializedDate | string | The serialized string representation of the date. |
| format | string | The format pattern used for deserialization (e.g., "YYYY-MM-DD"). |
Example
Deserialize a string into a Date object
const serializedDate = "2023-09-15"; // September 15, 2023
const deserializedDate = deserialize_date(serializedDate, "YYYY-MM-DD");
console.log('Deserialized date:', deserializedDate.toDateString()); // Output: Deserialized date: Wed Sep 15 2023
stringSerialize a JavaScript Date object into a string representation.
This function takes a JavaScript Date object and serializes it into a string representation based on a specified format pattern.
Kind: global function
Returns: string - The serialized string representation of the Date.
Remarks: - The function allows you to serialize a Date object into a custom format using format placeholders.
| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to serialize. |
| format | string | The format pattern for serializing the Date (e.g., "YYYY-MM-DD"). |
Example
Serialize a Date object into a custom format
const someDate = new Date(2023, 8, 15); // September 15, 2023
const formattedDate = serialize_date(someDate, "YYYY-MM-DD");
console.log('Formatted date:', formattedDate); // Output: Formatted date: 2023-09-15
booleanCheck if a JavaScript Date object falls within a specified date range.
This function takes a JavaScript Date object and checks if it falls within a specified date range defined by a start date and an end date, inclusive.
Kind: global function
Returns: boolean - True if the date is within the specified range, false otherwise.
Remarks: - The function checks if the provided Date object falls within the specified date range,
including the start and end dates.
true if the date is within the specified range and false otherwise.| Param | Type | Description |
|---|---|---|
| date | Date | The Date object to check. |
| startDate | Date | The start date of the date range (inclusive). |
| endDate | Date | The end date of the date range (inclusive). |
Example
Check if a Date object falls within a date range
const dateToCheck = new Date(2023, 8, 15); // September 15, 2023
const rangeStart = new Date(2023, 7, 1); // August 1, 2023
const rangeEnd = new Date(2023, 8, 30); // September 30, 2023
const isInRange = is_date_in_range(dateToCheck, rangeStart, rangeEnd);
console.log('Is in range:', isInRange); // Output: Is in range: true
numberGet the fiscal period for a JavaScript Date object within a fiscal year.
This function takes a JavaScript Date object and returns the fiscal period within a fiscal year to which the date belongs, based on a specified fiscal year start month.
Kind: global function
Returns: number - The fiscal period within the fiscal year (1 to 12) to which the date belongs.
Remarks: - The function calculates the fiscal period based on the month of the provided Date object and
the specified fiscal year start month.
| Param | Type | Description |
|---|---|---|
| date | Date | The Date object for which to get the fiscal period. |
| fiscalYearStartMonth | number | The month (1 to 12) in which the fiscal year starts. |
Example
Get the fiscal period for a Date object
const someDate = new Date(2023, 3, 15); // April 15, 2023
const fiscalPeriod = get_fiscal_period(someDate, 4); // Assuming fiscal year starts in April (month 4)
console.log('Fiscal Period:', fiscalPeriod); // Output: Fiscal Period: 12
numberGet the quarter of the year for a JavaScript Date object.
This function takes a JavaScript Date object and returns the quarter of the year (1 to 4) to which the date belongs.
Kind: global function
Returns: number - The quarter of the year (1 to 4) to which the date belongs.
Remarks: - The function calculates the quarter based on the month of the provided Date object.
| Param | Type | Description |
|---|---|---|
| date | Date | The Date object for which to get the quarter. |
Example
Get the quarter of the year for a Date object
const someDate = new Date(2023, 5, 15); // June 15, 2023
const quarter = get_quarter(someDate);
console.log('Quarter:', quarter); // Output: Quarter: 2
stringReads the entire content of a file and returns it as a string.
Kind: global function
Returns: string - The content of the file as a string.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to read. |
Example
const fileContent = read_file_contents('example.txt');
console.log(fileContent);
Writes data to a file, either by overwriting the existing content or appending to it.
Kind: global function
| Param | Type | Default | Description |
|---|---|---|---|
| filename | string | The path to the file to write to. | |
| data | string | The data to write to the file. | |
| append | boolean | false | Whether to append the data to the file (default: false). |
Example
write_to_file('example.txt', 'Hello, World!');
write_to_file('example.txt', ' Appended text.', true);
Copies the contents of one file to another.
Kind: global function
| Param | Type | Description |
|---|---|---|
| source | string | The path to the source file to copy from. |
| destination | string | The path to the destination file to copy to. |
Example
copy_file('source.txt', 'destination.txt');
Renames a file or moves it to a different directory.
Kind: global function
| Param | Type | Description |
|---|---|---|
| source | string | The current path of the file. |
| destination | string | The new path or directory of the file. |
Example
move_file('oldname.txt', 'newname.txt');
move_file('file.txt', 'directory/newfile.txt');
booleanChecks if a file exists at a specified path.
Kind: global function
Returns: boolean - true if the file exists, false otherwise.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to check. |
Example
if (file_exists('example.txt')) {
console.log('File exists!');
}
Deletes a file from the file system.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to delete. |
Example
delete_file('oldfile.txt');
numberDetermines the size of a file in bytes.
Kind: global function
Returns: number - The size of the file in bytes.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file. |
Example
const fileSize = get_file_size('document.pdf');
console.log(`File size: ${fileSize} bytes`);
stringDetermines the type or format of a file (e.g., text, binary, JSON, XML).
Kind: global function
Returns: string - The file type or format.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file. |
Example
const fileType = get_file_type('data.json');
console.log(`File type: ${fileType}`);
Sets or modifies file permissions (e.g., read, write, execute) on a file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file. |
| permissions | number | The permissions to set. |
Example
set_file_permissions('file.txt', 0o755); // Give read, write, and execute permissions to owner, and read and execute to others.
Promise.<Array.<any>>Reads data from a CSV file and parses it into a structured format (e.g., a list of dictionaries).
Kind: global function
Returns: Promise.<Array.<any>> - A Promise that resolves with an array of objects representing the CSV data.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the CSV file to read. |
Example
const csvData = await read_csv_file('data.csv');
console.log(csvData);
anyReads data from a JSON file and parses it into a dictionary or an object.
Kind: global function
Returns: any - The parsed JSON data.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the JSON file to read. |
Example
const jsonData = read_json_file('data.json');
console.log(jsonData);
Writes data from a dictionary or an object to a JSON file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the JSON file to write. |
| data | any | The data to write to the JSON file. |
Example
const data = { name: 'Alice', age: 30 };
write_json_file('output.json', data);
Compresses a file into an archive (e.g., ZIP).
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to compress. |
| archive_filename | string | The path and filename for the compressed archive. |
Example
compress_file('file.txt', 'file.zip');
Decompresses an archived file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| archive_filename | string | The path to the compressed archive file. |
| destination | string | The path to the destination directory. |
Example
decompress_file('file.zip', 'extracted/');
stringReads a text file while specifying the character encoding (e.g., UTF-8, UTF-16).
Kind: global function
Returns: string - The content of the text file as a string.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the text file to read. |
| encoding | crypto.Encoding | The character encoding to use (e.g., 'utf-8'). |
Example
const fileContent = read_text_file('textfile.txt', 'utf-8');
console.log(fileContent);
stringCalculates hash values (e.g., MD5, SHA-256) for a file's content.
Kind: global function
Returns: string - The calculated hash value.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file for which to calculate the hash. |
| hash_algorithm | string | The hash algorithm to use (e.g., 'md5', 'sha256'). |
Example
const md5Hash = calculate_file_hash('file.txt', 'md5');
console.log(`MD5 Hash: ${md5Hash}`);
booleanCompares two files to check if their contents are identical.
Kind: global function
Returns: boolean - true if the files have identical contents, false otherwise.
| Param | Type | Description |
|---|---|---|
| file1 | string | The path to the first file for comparison. |
| file2 | string | The path to the second file for comparison. |
Example
if (compare_files('file1.txt', 'file2.txt')) {
console.log('Files have identical contents.');
} else {
console.log('Files are not identical.');
}
booleanSearches for a specific string or pattern within a file.
Kind: global function
Returns: boolean - true if the pattern is found, false otherwise.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to search in. |
| search_pattern | string | RegExp | The string or regular expression to search for. |
Example
if (search_in_file('document.txt', 'keyword')) {
console.log('Pattern found in the file.');
} else {
console.log('Pattern not found.');
}
Creates backup copies of files in a specified directory.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to create a backup of. |
| backup_directory | string | The directory where backup copies will be stored. |
Example
backup_file('important.txt', 'backup/');
Changes the creation, modification, or access timestamps of a file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to modify timestamps for. |
| timestamp_type | string | The type of timestamp to change ('atime', 'mtime', or 'ctime'). |
| new_timestamp | Date | The new timestamp to set. |
Example
const newDate = new Date('2023-01-01T00:00:00Z');
change_file_timestamp('file.txt', 'mtime', newDate);
Merges the contents of multiple files into a single file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| output_filename | string | The path to the output file where merged content will be saved. |
| input_files | Array.<string> | An array of paths to the input files to be merged. |
Example
merge_files('merged.txt', ['file1.txt', 'file2.txt', 'file3.txt']);
Array.<Buffer>Reads a file in smaller chunks to conserve memory.
Kind: global function
Returns: Array.<Buffer> - An array of chunks.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to read. |
| chunk_size | number | The size of each chunk in bytes. |
Example
const chunks = read_file_in_chunks('largefile.txt', 1024); // Read in 1 KB chunks
booleanChecks the permissions of a file, such as whether it is readable, writable, or executable.
Kind: global function
Returns: boolean - true if the specified permission is granted, false otherwise.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to check permissions for. |
| permission_type | string | The type of permission to check ('read', 'write', 'execute'). |
Example
if (check_file_permissions('file.txt', 'read')) {
console.log('File is readable.');
} else {
console.log('File is not readable.');
}
Archives files into a single compressed file format (e.g., zip, tar).
Kind: global function
| Param | Type | Description |
|---|---|---|
| output_archive | string | The path and filename for the output archive. |
| input_files | Array.<string> | An array of paths to the input files to be archived. |
Example
archive_files('my_archive.zip', ['file1.txt', 'file2.txt']);
numberCounts the number of lines in a text file.
Kind: global function
Returns: number - The number of lines in the file.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the text file to count lines in. |
Example
const lineCount = count_lines_in_file('textfile.txt');
console.log(`Line count: ${lineCount}`);
Changes the owner of a file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to change ownership for. |
| new_owner | string | The username or UID of the new owner. |
Example
change_file_owner('file.txt', 'newuser');
Copies permissions from one file to another.
Kind: global function
| Param | Type | Description |
|---|---|---|
| source_file | string | The path to the source file to copy permissions from. |
| destination_file | string | The path to the destination file to apply permissions to. |
Example
copy_permissions('source.txt', 'destination.txt');
fs.StatsRetrieves metadata about a file, such as creation date, modification date, and size.
Kind: global function
Returns: fs.Stats - An object containing file metadata.
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to retrieve metadata for. |
Example
const metadata = get_file_metadata('file.txt');
console.log(metadata);
Encrypts a file using a specified encryption key.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to encrypt. |
| encryption_key | string | The encryption key. |
Example
encrypt_file('file.txt', 'mysecretkey');
Decrypts an encrypted file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| encrypted_filename | string | The path to the encrypted file. |
| decryption_key | string | The decryption key. |
Example
decrypt_file('encrypted.txt', 'mysecretkey');
Modifies a specific line in a text file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the text file. |
| line_number | number | The line number to modify (1-based index). |
| new_content | string | The new content to replace the line with. |
Example
modify_line_in_file('textfile.txt', 3, 'Updated line content');
Removes specific permissions from a file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to remove permissions from. |
| permissions | string | The permissions to remove (e.g., 'read', 'write', 'execute'). |
Example
remove_file_permissions('file.txt', 'write');
Uploads a file to a remote server.
Kind: global function
| Param | Type | Description |
|---|---|---|
| local_filename | string | The path to the local file to upload. |
| remote_destination | string | The destination on the remote server where the file will be uploaded. |
Example
upload_file('localfile.txt', 'remote_server:/path/to/destination/');
Downloads a file from a remote server.
Kind: global function
| Param | Type | Description |
|---|---|---|
| remote_filename | string | The path to the file on the remote server to download. |
| local_destination | string | The local destination where the file will be saved. |
Example
download_file('remote_server:/path/to/remotefile.txt', 'localfile.txt');
Converts the encoding of a text file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| input_filename | string | The path to the input file with the source encoding. |
| output_filename | string | The path to the output file with the target encoding. |
| source_encoding | string | The source encoding of the file (e.g., 'utf-8', 'utf-16'). |
| target_encoding | string | The target encoding to convert the file to (e.g., 'utf-8', 'utf-16'). |
Example
convert_file_encoding('file.txt', 'converted.txt', 'utf-8', 'utf-16');
Filters lines in a text file based on a custom filter function.
Kind: global function
| Param | Type | Description |
|---|---|---|
| input_filename | string | The path to the input text file. |
| output_filename | string | The path to the output text file with filtered lines. |
| filter_function | function | The custom filter function that determines which lines to keep. |
Example
Example filter function that keeps lines containing the word 'apple'
function filter_function(line) {
return line.includes('apple');
}
filter_file_lines('input.txt', 'output.txt', filter_function);
Checks if a file is owned by a specific user.
Kind: global function
| Param | Type | Description |
|---|---|---|
| filename | string | The path to the file to check ownership. |
| user | string | The user to check ownership against. |
Example
check_file_ownership('file.txt', 'john');
Rotates and manages a limited number of backup copies of a file.
Kind: global function
| Param | Type | Description |
|---|---|---|
| backup_directory | string | The directory where backup copies will be stored. |
| max_backups | number | The maximum number of backup copies to retain. |
Example
rotate_file_backups('/backup', 5);
Array.<string>Extracts the names of all function declarations, function expressions, and arrow functions from a TypeScript file and returns them as an array.
Kind: global function
Returns: Array.<string> - An array containing the names of all functions found in the file.
Throws:
Error Throws an error if there's an issue reading the file or parsing its content.| Param | Type | Description |
|---|---|---|
| filePath | string | The path to the TypeScript file to be analyzed. |
Example
Example usage:
const filePath = 'yourTypeScriptFile.ts'; // Replace with your file path
const functionNames = getFunctionNamesInFile(filePath);
console.log('Function names in the file:', functionNames);
Distance between two points on a geo map coordinate sysytem in Kilometer
Kind: global function
Returns: (type: number) Distance between (lat1, lon1) point and (lat2, long2) point in Kilometers.
| Param | Description |
|---|---|
| lat1 | (type: number) latitude1 |
| lon1 | (type: number) longitude1 |
| lat2 | (type: number) latitude2 |
| lon2 | (type: number) longitude2 |
Promise.<GeolocationPosition>This function uses the browser's Geolocation API to obtain the user's current geographical position.
It returns a Promise that resolves with a GeolocationPosition object containing the latitude,
longitude, and other information about the user's location.
If the Geolocation API is not available in the user's browser, it will throw an error. You can catch and handle this error to provide a fallback or alternative experience for users who do not have geolocation capabilities in their browser.
Kind: global function
Returns: Promise.<GeolocationPosition> - A Promise that resolves with the user's current geolocation.
Throws:
Error Throws an error if geolocation is not available in the browser.Example
try {
const position = await getUserLocation();
console.log(`Latitude: ${position.coords.latitude}, Longitude: ${position.coords.longitude}`);
} catch (error) {
console.error(`Error getting user location: ${error.message}`);
}
numberThis function calculates the great-circle distance between two points on the Earth's surface using the Haversine formula. It provides accurate results for short to moderate distances.
Kind: global function
Returns: number - The distance between the two coordinates in meters.
| Param | Type | Description |
|---|---|---|
| lat1 | number | Latitude of the first point in degrees. |
| lon1 | number | Longitude of the first point in degrees. |
| lat2 | number | Latitude of the second point in degrees. |
| lon2 | number | Longitude of the second point in degrees. |
Example
const distance = calculateDistance(40.7128, -74.0060, 34.0522, -118.2437);
console.log(`Distance: ${distance.toFixed(2)} meters`);
numberThis function calculates the initial bearing from the first set of coordinates to the second set of coordinates using the formula for the initial bearing of a great circle route.
Kind: global function
Returns: number - The initial bearing in degrees (0° to 360°).
| Param | Type | Description |
|---|---|---|
| lat1 | number | Latitude of the first point in degrees. |
| lon1 | number | Longitude of the first point in degrees. |
| lat2 | number | Latitude of the second point in degrees. |
| lon2 | number | Longitude of the second point in degrees. |
Example
const bearing = calculateBearing(40.7128, -74.0060, 34.0522, -118.2437);
console.log(`Initial Bearing: ${bearing.toFixed(2)} degrees`);
booleanThis function checks if the provided latitude and longitude values fall within the valid range for Earth's coordinates. Latitude should be between -90 and 90 degrees, and longitude should be between -180 and 180 degrees.
Kind: global function
Returns: boolean - True if the coordinates are valid, false otherwise.
| Param | Type | Description |
|---|---|---|
| lat | number | Latitude to check (-90 to 90 degrees). |
| lon | number | Longitude to check (-180 to 180 degrees). |
Example
const isValid = areCoordinatesValid(40.7128, -74.0060);
console.log(`Coordinates are valid: ${isValid}`);
stringThis function takes a distance in meters and converts it to a human-readable format with the specified units. You can use 'metric' for kilometers or 'imperial' for miles.
Kind: global function
Returns: string - The formatted distance with units.
| Param | Type | Description |
|---|---|---|
| distanceInMeters | number | Distance in meters to format. |
| units | 'metric' | 'imperial' | Units to use ('metric' for kilometers, 'imperial' for miles). |
Example
const distanceInMeters = 1500;
const formattedDistance = formatDistance(distanceInMeters, 'metric');
console.log(`Distance: ${formattedDistance}`);
numberThis function converts a distance in meters to pixels on a map with a fixed scale. You need to provide the distance in meters and the scale in meters per pixel for the map.
Kind: global function
Returns: number - The equivalent distance in pixels.
| Param | Type | Description |
|---|---|---|
| distanceInMeters | number | Distance in meters to convert to pixels. |
| scaleInMetersPerPixel | number | Map's scale in meters per pixel. |
Example
const distanceInMeters = 1000;
const scaleInMetersPerPixel = 10; // 10 meters per pixel on the map
const distanceInPixels = metersToPixels(distanceInMeters, scaleInMetersPerPixel);
console.log(`Distance in pixels: ${distanceInPixels}`);
Kind: global function
Returns: args
| Param |
|---|
| args |
Parses and returns info about the call stack at the given index. Copied Code from Src: https://gist.github.com/ManotLuijiu/8f0be2f0ac0a8f6dd5dc47e2db332600
Initiate a Logger
Kind: global function
Returns: logger object
| Param | Description |
|---|---|
| fileUrl | URL of File for storage. |
Initiate a Logger
Kind: global function
Returns: logger object
| Param | Type | Description |
|---|---|---|
| fileUrl | string | URL of File for storage. |
numberCalculates the absolute value of a given number.
Kind: global function
Returns: number - The absolute value of the input number.
Throws:
Error Throws an error if the input is not a valid number.Remarks: This function returns the absolute value of a number, which is always non-negative.
If the input number is negative, the function returns its negation to make it positive.
Remarks: An error is thrown if the input is not a valid number.
| Param | Type | Description |
|---|---|---|
| num | number | The number for which to calculate the absolute value. |
Example
Example 1:
const result1 = absolute(-5); Returns 5
Example 2:
const result2 = absolute(10); Returns 10 (unchanged since it's already positive)
numberCalculates the square root of a given number.
Kind: global function
Returns: number - The square root of the input number.
Throws:
Error Throws an error if the input is not a valid number or if it's negative.Remarks: This function computes the square root of a number using the power operator (**). It throws an error if the input is not a valid number or if it's negative, as the square root is not defined for negative numbers.
| Param | Type | Description |
|---|---|---|
| num | number | The number for which to calculate the square root. |
Example
Example 1:
const result1 = squareRoot(16); Returns 4
Example 2:
const result2 = squareRoot(9); Returns 3
numberCalculates the cube root of a given number.
Kind: global function
Returns: number - The cube root of the input number.
Throws:
Error Throws an error if the input is not a valid number or if it's negative.Remarks: This function computes the cube root of a number using the power operator (**). It throws an error if the input is not a valid number.
| Param | Type | Description |
|---|---|---|
| num | number | The number for which to calculate the cube root. |
Example
Example 1:
const result1 = cubeRoot(8); Returns 2
Example 2:
const result2 = cubeRoot(27); Returns 3
numberMultiplies all the numbers in an array.
Kind: global function
Returns: number - The result of multiplying all the numbers in the array.
Throws:
Error Throws an error if the input is not a valid array of numbers or if the array is empty.Remarks: This function multiplies all the numbers in the given array and returns the result. It throws an error if the input is not a valid array of numbers or if the array is empty.
| Param | Type | Description |
|---|---|---|
| array | Array.<number> | An array of numbers to be multiplied. |
Example
Example 1:
const result1: number = multiplyArray([2, 3, 4]); Returns 24
Example 2:
const result2: number = multiplyArray([]); Throws an error (empty array)
numberCalculates the geometric mean of numbers in an array.
Kind: global function
Returns: number - The geometric mean of the numbers in the input array.
Throws:
Error Throws an error if the input is not a valid array of numbers or if the array is empty.Remarks: The geometric mean is calculated by multiplying all the numbers in the array and taking the nth root, where n is the number of elements in the array. It throws an error if the input is not a valid array of numbers or if the array is empty.
| Param | Type | Description |
|---|---|---|
| array | Array.<number> | An array of numbers for which to calculate the geometric mean. |
Example
Example 1:
const result1: number = geometricMean([2, 4, 8]); Returns 4
Example 2:
const result2: number = geometricMean([]); Throws an error (empty array)
numberCalculates the median of numbers in an array.
Kind: global function
Returns: number - The median of the numbers in the input array.
Throws:
Error Throws an error if the input is not a valid array of numbers or if the array is empty.Remarks: The median is calculated by sorting the input array and finding the middle value. If the array has an even number of elements, the median is the average of the two middle values. It throws an error if the input is not a valid array of numbers or if the array is empty.
| Param | Type | Description |
|---|---|---|
| array | Array.<number> | An array of numbers for which to calculate the median. |
Example
Example 1:
const result1: number = median([2, 4, 8]); Returns 4
Example 2:
const result2: number = median([]); Throws an error (empty array)
numberFinds the mode (most frequently occurring value) in an array of numbers.
Kind: global function
Returns: number - The mode of the numbers in the input array.
Throws:
Error Throws an error if the input is not a valid array of numbers or if the array is empty.Remarks: The mode is the value that appears most frequently in the input array. It throws an error if the input is not a valid array of numbers or if the array is empty.
| Param | Type | Description |
|---|---|---|
| array | Array.<number> | An array of numbers for which to find the mode. |
Example
Example 1:
const result1: number = mode([2, 2, 3, 4, 4, 4, 5]); Returns 4
Example 2:
const result2: number = mode([]); Throws an error (empty array)
numberCalculates the mean squared error of an array of numbers.
Kind: global function
Returns: number - The mean squared error of the numbers in the input array.
Throws:
Error Throws an error if the input is not a valid array of numbers or if the array is empty.Remarks: The mean squared error is calculated as the average of the squared differences between each element and the mean of the array. It measures the average squared deviation from the mean. It throws an error if the input is not a valid array of numbers or if the array is empty.
| Param | Type | Description |
|---|---|---|
| array | Array.<number> | An array of numbers for which to calculate the mean squared error. |
Example
Example 1:
const result1: number = meanSquareError([2, 4, 8]); Returns 6.666666666666667
Example 2:
const result2: number = meanSquareError([]); Throws an error (empty array)
numberCalculates the variance of an array of numbers.
Kind: global function
Returns: number - The variance of the numbers in the input array.
Throws:
Error Throws an error if the input is not a valid array of numbers or if the array is empty.Remarks: The variance is calculated as the mean squared error divided by the number of elements in the array. It throws an error if the input is not a valid array of numbers or if the array is empty.
| Param | Type | Description |
|---|---|---|
| array | Array.<number> | An array of numbers for which to calculate the variance. |
Example
Example 1:
const result1: number = variance([2, 4, 8]); Returns 6.666666666666667
Example 2:
const result2: number = variance([]); Throws an error (empty array)
numberCalculates the standard deviation of an array of numbers.
Kind: global function
Returns: number - The standard deviation of the numbers in the input array.
Throws:
Error Throws an error if the input is not a valid array of numbers or if the array is empty.Remarks: The standard deviation is calculated as the square root of the variance. It throws an error if the input is not a valid array of numbers or if the array is empty.
| Param | Type | Description |
|---|---|---|
| array | Array.<number> | An array of numbers for which to calculate the standard deviation. |
Example
Example 1:
const result1: number = standardDeviation([2, 4, 8]); Returns approximately 2.160246899469287
Example 2:
const result2: number = standardDeviation([]); Throws an error (empty array)
Array.<number>Calculates the rank and value of a given percentile in an array of numbers.
Kind: global function
Returns: Array.<number> - An array containing the rank and value corresponding to the percentile.
Throws:
Error Throws an error if the input is not a valid array of numbers or if the percentile is out of range.Remarks: The percentile rank is calculated as the rank (position) of the value that corresponds to the given percentile. It throws an error if the input is not a valid array of numbers or if the percentile is out of range.
| Param | Type | Description |
|---|---|---|
| array | Array.<number> | An array of numbers for which to calculate the percentile rank. |
| percentile | number | The percentile (0 to 100) for which to calculate the rank and value. |
Example
Example 1:
const result1: [number, number] = percentileRank([1, 2, 3, 4, 5], 50); Returns [3, 3]
Example 2:
const result2: [number, number] = percentileRank([], 75); Throws an error (empty array)
numberCalculates the percentile rank of a given value in an array of numbers.
Kind: global function
Returns: number - The percentile rank of the given value in the input array (0 to 100).
Throws:
Error Throws an error if the input is not a valid array of numbers or if the value is not found in the array.Remarks: The percentile rank is calculated as the rank (position) of the given value in the array, expressed as a percentage of the array length. It throws an error if the input is not a valid array of numbers or if the value is not found in the array.
| Param | Type | Description |
|---|---|---|
| array | Array.<number> | An array of numbers for which to calculate the percentile rank. |
| key | number | The value for which to calculate the percentile rank. |
Example
Example 1:
const result1: number = percentile([1, 2, 3, 4, 5], 3); Returns 60
Example 2:
const result2: number = percentile([], 75); Throws an error (empty array)
numberAdds a percentage to a given number.
Kind: global function
Returns: number - The result of adding the percentage to the number.
Remarks: This function adds the specified percentage to the given number.
| Param | Type | Description |
|---|---|---|
| num | number | The number to which to add the percentage. |
| percentage | number | The percentage to add to the number. |
Example
Example 1:
const result1: number = addPercentage(100, 10); Returns 110
Example 2:
const result2: number = addPercentage(50, -20); Returns 40
numberCalculates the sine of an angle in radians.
Kind: global function
Returns: number - The sine of the given angle in radians.
Remarks: This function calculates the sine of the given angle in radians using the Math.sin function.
| Param | Type | Description |
|---|---|---|
| radians | number | The angle in radians for which to calculate the sine. |
Example
Example 1:
const result1: number = sin(Math.PI / 2); Returns 1 (sine of 90 degrees)
Example 2:
const result2: number = sin(0); Returns 0 (sine of 0 degrees)
numberCalculates the cosine of an angle in radians.
Kind: global function
Returns: number - The cosine of the given angle in radians.
Remarks: This function calculates the cosine of the given angle in radians using the Math.cos function.
| Param | Type | Description |
|---|---|---|
| radians | number | The angle in radians for which to calculate the cosine. |
Example
Example 1:
const result1: number = cos(Math.PI / 3); Returns 0.5 (cosine of 60 degrees)
Example 2:
const result2: number = cos(0); Returns 1 (cosine of 0 degrees)
numberCalculates the tangent of an angle in radians.
Kind: global function
Returns: number - The tangent of the given angle in radians.
Remarks: This function calculates the tangent of the given angle in radians using the Math.tan function.
| Param | Type | Description |
|---|---|---|
| radians | number | The angle in radians for which to calculate the tangent. |
Example
Example 1:
const result1: number = tan(Math.PI / 4); Returns 1 (tangent of 45 degrees)
Example 2:
const result2: number = tan(0); Returns 0 (tangent of 0 degrees)
numberCalculates the cosecant (csc) of an angle in radians.
Kind: global function
Returns: number - The cosecant of the given angle in radians.
Remarks: This function calculates the cosecant (csc) of the given angle in radians as the reciprocal of the sine.
| Param | Type | Description |
|---|---|---|
| radians | number | The angle in radians for which to calculate the cosecant. |
Example
Example 1:
const result1: number = cosec(Math.PI / 6); Returns 2 (cosecant of 30 degrees)
Example 2:
const result2: number = cosec(Math.PI / 2); Returns 1 (cosecant of 90 degrees)
numberCalculates the secant (sec) of an angle in radians.
Kind: global function
Returns: number - The secant of the given angle in radians.
Remarks: This function calculates the secant (sec) of the given angle in radians as the reciprocal of the cosine.
| Param | Type | Description |
|---|---|---|
| radians | number | The angle in radians for which to calculate the secant. |
Example
Example 1:
const result1: number = sec(Math.PI / 4); Returns approximately 1.4142135623730951 (secant of 45 degrees)
Example 2:
const result2: number = sec(Math.PI / 6); Returns 2 (secant of 30 degrees)
numberCalculates the cotangent (cot) of an angle in radians.
Kind: global function
Returns: number - The cotangent of the given angle in radians.
Remarks: This function calculates the cotangent (cot) of the given angle in radians as the reciprocal of the tangent.
| Param | Type | Description |
|---|---|---|
| radians | number | The angle in radians for which to calculate the cotangent. |
Example
Example 1:
const result1: number = cot(Math.PI / 4); Returns 1 (cotangent of 45 degrees)
Example 2:
const result2: number = cot(Math.PI / 6); Returns approximately 1.7320508075688772 (cotangent of 30 degrees)
numberCalculates the arcsine (inverse sine) of a number.
Kind: global function
Returns: number - The arcsine (inverse sine) of the given number in radians.
Remarks: This function calculates the arcsine (inverse sine) of the given number in radians using the Math.asin function.
| Param | Type | Description |
|---|---|---|
| num | number | The number for which to calculate the arcsine in radians. |
Example
Example 1:
const result1: number = asin(0.5); Returns approximately 0.5235987755982989 (arcsine of 0.5)
Example 2:
const result2: number = asin(1); Returns approximately 1.5707963267948966 (arcsine of 1)
numberCalculates the arccosine (inverse cosine) of a number.
Kind: global function
Returns: number - The arccosine (inverse cosine) of the given number in radians.
Remarks: This function calculates the arccosine (inverse cosine) of the given number in radians using the Math.acos function.
| Param | Type | Description |
|---|---|---|
| num | number | The number for which to calculate the arccosine in radians. |
Example
Example 1:
const result1: number = acos(0.5); Returns approximately 1.0471975511965979 (arccosine of 0.5)
Example 2:
const result2: number = acos(1); Returns 0 (arccosine of 1)
numberCalculates the arctangent (inverse tangent) of a number.
Kind: global function
Returns: number - The arctangent (inverse tangent) of the given number in radians.
Remarks: This function calculates the arctangent (inverse tangent) of the given number in radians using the Math.atan function.
| Param | Type | Description |
|---|---|---|
| num | number | The number for which to calculate the arctangent in radians. |
Example
Example 1:
const result1: number = atan(1); Returns approximately 0.7853981633974483 (arctangent of 1)
Example 2:
const result2: number = atan(0); Returns 0 (arctangent of 0)
numberCalculates the arccosecant (inverse cosecant) of a number.
Kind: global function
Returns: number - The arccosecant (inverse cosecant) of the given number in radians.
Remarks: This function calculates the arccosecant (inverse cosecant) of the given number in radians as the reciprocal of the arcsine.
| Param | Type | Description |
|---|---|---|
| num | number | The number for which to calculate the arccosecant in radians. |
Example
Example 1:
const result1: number = acosec(2); Returns approximately 1.5707963267948966 (arccosecant of 2)
Example 2:
const result2: number = acosec(1); Returns approximately 1.5707963267948966 (arccosecant of 1)
numberCalculates the arcsecant (inverse secant) of a number.
Kind: global function
Returns: number - The arcsecant (inverse secant) of the given number in radians.
Remarks: This function calculates the arcsecant (inverse secant) of the given number in radians as the reciprocal of the arccosine.
| Param | Type | Description |
|---|---|---|
| num | number | The number for which to calculate the arcsecant in radians. |
Example
Example 1:
const result1: number = asec(2); Returns approximately 1.0471975511965979 (arcsecant of 2)
Example 2:
const result2: number = asec(1); Returns 0 (arcsecant of 1)
numberCalculates the arccotangent (inverse cotangent) of a number.
Kind: global function
Returns: number - The arccotangent (inverse cotangent) of the given number in radians.
Remarks: This function calculates the arccotangent (inverse cotangent) of the given number in radians as the reciprocal of the arctangent.
| Param | Type | Description |
|---|---|---|
| num | number | The number for which to calculate the arccotangent in radians. |
Example
Example 1:
const result1: number = acot(2); Returns approximately 0.4636476090008061 (arccotangent of 2)
Example 2:
const result2: number = acot(1); Returns approximately 0.7853981633974483 (arccotangent of 1)
numberCalculates the arctangent of the quotient of its arguments, taking signs into account.
Kind: global function
Returns: number - The arctangent of the quotient of x and y in radians.
Remarks: This function calculates the arctangent of the quotient of x and y in radians using the Math.atan2 function.
| Param | Type | Description |
|---|---|---|
| x | number | The y-coordinate. |
| y | number | The x-coordinate. |
Example
Example 1:
const result1: number = atan2(1, 1); Returns approximately 0.7853981633974483 (arctangent of 1/1)
Example 2:
const result2: number = atan2(-1, -1); Returns approximately -2.356194490192345 (arctangent of -1/-1)
numberCalculates the Euclidean distance between two points (x1, y1) and (x2, y2) in a 2D plane.
Kind: global function
Returns: number - The Euclidean distance between the two points.
Remarks: This function calculates the Euclidean distance between two points (x1, y1) and (x2, y2) in a 2D plane.
| Param | Type | Description |
|---|---|---|
| x1 | number | The x-coordinate of the first point. |
| y1 | number | The y-coordinate of the first point. |
| x2 | number | The x-coordinate of the second point. |
| y2 | number | The y-coordinate of the second point. |
Example
Example 1:
const result1: number = distance(0, 0, 3, 4); Returns 5 (distance between (0,0) and (3,4))
Example 2:
const result2: number = distance(1, 2, 1, 2); Returns 0 (distance between identical points)
numberConverts degrees to radians.
Kind: global function
Returns: number - The equivalent angle in radians.
Remarks: This function converts an angle from degrees to radians by multiplying it by the conversion factor (Math.PI / 180).
| Param | Type | Description |
|---|---|---|
| degree | number | The angle in degrees to convert to radians. |
Example
Example 1:
const result1: number = deg2Rad(90); Returns approximately 1.5707963267948966 (90 degrees in radians)
Example 2:
const result2: number = deg2Rad(180); Returns approximately 3.141592653589793 (180 degrees in radians)
numberConverts radians to degrees.
Kind: global function
Returns: number - The equivalent angle in degrees.
Remarks: This function converts an angle from radians to degrees by multiplying it by the conversion factor (180 / Math.PI).
| Param | Type | Description |
|---|---|---|
| radians | number | The angle in radians to convert to degrees. |
Example
Example 1:
const result1: number = rad2Deg(Math.PI / 2); Returns 90 (π/2 radians in degrees)
Example 2:
const result2: number = rad2Deg(Math.PI); Returns 180 (π radians in degrees)
numberConverts a temperature in degrees Celsius to degrees Fahrenheit.
Kind: global function
Returns: number - The equivalent temperature in degrees Fahrenheit.
Remarks: This function converts a temperature from degrees Celsius to degrees Fahrenheit using the formula (Celsius * 9/5) + 32.
| Param | Type | Description |
|---|---|---|
| celsius | number | The temperature in degrees Celsius to convert to degrees Fahrenheit. |
Example
Example 1:
const result1: number = celsius2fahren(0); Returns 32 (0°C in °F)
Example 2:
const result2: number = celsius2fahren(100); Returns 212 (100°C in °F)
numberConverts a temperature in degrees Fahrenheit to degrees Celsius.
Kind: global function
Returns: number - The equivalent temperature in degrees Celsius.
Remarks: This function converts a temperature from degrees Fahrenheit to degrees Celsius using the formula (Fahrenheit - 32) * 5/9.
| Param | Type | Description |
|---|---|---|
| fahrenheit | number | The temperature in degrees Fahrenheit to convert to degrees Celsius. |
Example
Example 1:
const result1: number = fahren2celsius(32); Returns 0 (32°F in °C)
Example 2:
const result2: number = fahren2celsius(212); Returns 100 (212°F in °C)
numberConverts a temperature in degrees Celsius to Kelvin.
Kind: global function
Returns: number - The equivalent temperature in Kelvin.
Remarks: This function converts a temperature from degrees Celsius to Kelvin by adding 273.15.
| Param | Type | Description |
|---|---|---|
| celsius | number | The temperature in degrees Celsius to convert to Kelvin. |
Example
Example 1:
const result1: number = celsius2kelvin(0); Returns 273.15 (0°C in Kelvin)
Example 2:
const result2: number = celsius2kelvin(100); Returns 373.15 (100°C in Kelvin)
numberConverts a temperature in Kelvin to degrees Celsius.
Kind: global function
Returns: number - The equivalent temperature in degrees Celsius.
Remarks: This function converts a temperature from Kelvin to degrees Celsius by subtracting 273.15.
| Param | Type | Description |
|---|---|---|
| kelvin | number | The temperature in Kelvin to convert to degrees Celsius. |
Example
Example 1:
const result1: number = kelvin2celsius(273.15); Returns 0 (273.15K in °C)
Example 2:
const result2: number = kelvin2celsius(373.15); Returns 100 (373.15K in °C)
numberConverts a temperature in degrees Fahrenheit to Kelvin.
Kind: global function
Returns: number - The equivalent temperature in Kelvin.
Remarks: This function converts a temperature from degrees Fahrenheit to Kelvin using the formula (Fahrenheit - 32) * 5/9 + 273.15.
| Param | Type | Description |
|---|---|---|
| fahrenheit | number | The temperature in degrees Fahrenheit to convert to Kelvin. |
Example
Example 1:
const result1: number = fahren2kelvin(32); Returns 273.15 (32°F in Kelvin)
Example 2:
const result2: number = fahren2kelvin(212); Returns 373.15 (212°F in Kelvin)
numberConverts a temperature in Kelvin to degrees Fahrenheit.
Kind: global function
Returns: number - The equivalent temperature in degrees Fahrenheit.
Remarks: This function converts a temperature from Kelvin to degrees Fahrenheit using the formula (Kelvin - 273.15) * 9/5 + 32.
| Param | Type | Description |
|---|---|---|
| kelvin | number | The temperature in Kelvin to convert to degrees Fahrenheit. |
Example
Example 1:
const result1: number = kelvin2fahren(273.15); Returns 32 (273.15K in °F)
Example 2:
const result2: number = kelvin2fahren(373.15); Returns 212 (373.15K in °F)
stringSerialize an object to a JSON-formatted string.
Kind: global function
Returns: string - The JSON-formatted string representation of the object.
| Param | Type | Description |
|---|---|---|
| object | T | The object to serialize. |
Example
const data = { name: 'John', age: 30 };
const jsonString = serializeJson(data);
Returns '{"name":"John","age":30}'
T | nullDeserialize a JSON-formatted string into a JavaScript object.
Kind: global function
Returns: T | null - The JavaScript object deserialized from the string, or null if parsing fails.
| Param | Type | Description |
|---|---|---|
| serializedData | string | The JSON-formatted string to deserialize. |
Example
const jsonString = '{"name":"John","age":30}';
const data = deSerializeJson<Data>(jsonString);
Returns { name: 'John', age: 30 }
string | nullSerializes data into a string representation.
Kind: global function
Returns: string | null - The serialized data as a string, or null if serialization fails.
| Param | Type | Description |
|---|---|---|
| data | T | The data to be serialized. |
| [options] | SerializationOptions | Serialization options (optional). |
Example
const dataToSerialize = { name: "John", age: 30 };
const serializedData = serialize(dataToSerialize, { prettyPrint: true });
if (serializedData !== null) {
console.log(serializedData);
}
stringSerialize data to CSV format with optional serialization options.
Kind: global function
Returns: string - The CSV representation of the data.
Throws:
Error Throws an error if serialization fails (when throwError is true).| Param | Type | Description |
|---|---|---|
| data | Array.<T> | The data to be serialized. |
| [options] | CSVSerializationOptions | Serialization options (optional). |
Example
const data = [...]; // Data to be serialized to CSV
const csv = serializeCSV(data);
console.log(csv);
T | nullDeserializes a string into a custom data type using a provided deserialization function.
Kind: global function
Returns: T | null - The deserialized data or null if deserialization fails.
| Param | Type | Description |
|---|---|---|
| serializedData | string | The serialized data as a string. |
| customDeserializer | function | A custom deserialization function that converts the serialized data into the desired data type. |
Example
Define a custom deserialization function
function customDeserializer(serializedData) {
// Implement your deserialization logic here
// For example, parse JSON or decode a custom format
return deserializedData;
}
Deserialize data using the custom deserializer
const serializedData = /* Serialized data as a string * /;
const deserializedData = deserialize(serializedData, customDeserializer);
console.log(deserializedData); // Output: The deserialized data or null if deserialization fails
Array.<T> | nullDeserializes a CSV string into an array of objects, where each object represents a row of data.
Kind: global function
Returns: Array.<T> | null - An array of objects representing the CSV data or null if the CSV format is invalid.
Throws:
Error If the CSV format is invalid or a data row has an incorrect number of fields.| Param | Type | Description |
|---|---|---|
| csvString | string | The CSV data as a string. |
Example
Deserialize CSV data
const csvString = /* CSV data as a string * /;
const deserializedData = deserializeCSV(csvString);
console.log(deserializedData); // Output: An array of objects representing CSV data or null if the format is invalid.
TDeep clones an object, including nested objects and arrays.
Kind: global function
Returns: T - The deep-cloned data.
| Param | Type | Description |
|---|---|---|
| data | T | The data to be deep-cloned. |
Example
const originalObject = {
name: "John",
address: {
city: "New York",
zipCode: "10001"
},
hobbies: ["Reading", "Traveling"]
};
const clonedObject = deepClone(originalObject);
console.log(clonedObject);
booleanDeeply compares two objects for equality, including nested objects and arrays.
Kind: global function
Returns: boolean - True if the objects are deeply equal, false otherwise.
Remarks: This function performs a deep comparison between two objects, including all of their nested properties and arrays. It checks if the objects have the same structure and values at all levels of nesting.
Remarks: By default, arrays are compared deeply. You can disable deep comparison of arrays by setting the compareArrays option to false in the options parameter.
| Param | Type | Description |
|---|---|---|
| obj1 | T | The first object to compare. |
| obj2 | T | The second object to compare. |
| [options] | DeepEqualityOptions | Deep equality comparison options (optional). |
Example
const object1 = {
name: "John",
address: {
city: "New York",
zipCode: "10001"
},
hobbies: ["Reading", "Traveling"]
};
const object2 = {
name: "John",
address: {
city: "New York",
zipCode: "10001"
},
hobbies: ["Reading", "Traveling"]
};
const isEqual = deepEqual(object1, object2);
console.log(isEqual); // true
ValidationResultValidates an object against a JSON schema.
Kind: global function
Returns: ValidationResult - An object indicating whether the data is valid and, if not, any validation errors.
Remarks: This function uses the ajv (Another JSON Schema Validator) library to validate an object (data) against a provided JSON schema (schema). The schema defines the expected structure and data types for the object. The function returns an object containing a boolean isValid property that indicates whether the data is valid and an array of errors if validation fails.
| Param | Type | Description |
|---|---|---|
| data | T | The data object to be validated. |
| schema | object | The JSON schema to validate against. |
Example
const data = {
name: "John",
age: 30,
};
const schema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "number" },
},
required: ["name", "age"],
};
const validationResult = validateSchema(data, schema);
if (validationResult.isValid) {
console.log("Data is valid!");
} else {
console.error("Validation errors:", validationResult.errors);
}
Uint8ArrayCompresses data using the specified compression algorithm.
Kind: global function
Returns: Uint8Array - The compressed data as a Uint8Array.
Throws:
Error Throws an error if an unsupported compression algorithm is specified in the options parameter. Supported values for the algorithm option are "deflate" (default) for compression and "inflate" for decompression.Remarks: This function allows you to compress data using the specified compression algorithm. The supported compression algorithms are "deflate" (for compression) and "inflate" (for decompression).
Remarks: If the data parameter is provided as a string, it will be internally converted to a Uint8Array using the TextEncoder API before compression.
| Param | Type | Description |
|---|---|---|
| data | Uint8Array | string | The data to be compressed, either as a Uint8Array or a string. |
| [options] | CompressionOptions | Compression options (optional). |
Example
const dataToCompress = "This is some data to compress.";
const compressedData = compress(dataToCompress);
console.log(compressedData);
Uint8Array | stringDecompresses compressed data using either the "inflate" or "deflate" algorithm.
Kind: global function
Returns: Uint8Array | string - The decompressed data as a Uint8Array or string.
Throws:
Error If an unsupported decompression algorithm is specified.| Param | Type | Description |
|---|---|---|
| compressedData | Uint8Array | The compressed data to decompress. |
| [options] | CompressionOptions | Optional decompression options. |
Example
const compressedData = /* Compressed data here * /;
Decompress using the default "inflate" algorithm
const decompressedData = decompress(compressedData);
console.log(decompressedData); // Output: "Decompressed string data"
Decompress using the "deflate" algorithm
const decompressedDataDeflate = decompress(compressedData, { algorithm: 'deflate' });
console.log(decompressedDataDeflate); // Output: "Decompressed string data"
string | nullConverts data to JSON format with optional formatting options.
Kind: global function
Returns: string | null - Returns the JSON representation of the data as a string if the conversion is successful. If the conversion fails due to invalid input data, it returns null.
Remarks: This function allows you to convert various types of data to JSON format with optional formatting options. You can specify whether you want the JSON output to be pretty-printed (indented) or in compact format (default).
| Param | Type | Description |
|---|---|---|
| data | any | The data to be converted to JSON. |
| [options] | JSONOptions | JSON formatting options (optional). |
Example
const dataToConvert = { name: "John", age: 30 };
const jsonData = convertToJSON(dataToConvert, { prettyPrint: true });
console.log(jsonData);
any | nullConverts JSON data to its JavaScript representation with optional parsing options.
Kind: global function
Returns: any | null - Returns the JavaScript representation of the JSON data if the parsing is successful. If the parsing fails due to invalid JSON, it returns null.
Remarks: This function allows you to convert JSON data to its JavaScript representation with optional parsing options. You can specify whether to use a reviver function and configure error handling behavior.
| Param | Type | Description |
|---|---|---|
| jsonData | string | The JSON data to be converted to JavaScript. |
| [options] | JSONOptions | JSON parsing options (optional). |
Example
const jsonData = '{"name": "John", "age": 30}';
const jsData = convertFromJSON(jsonData);
console.log(jsData);
voidHandles serialization errors with optional error-handling options.
Kind: global function
Throws:
Error Throws an error if the error-handling options are invalid.| Param | Type | Description |
|---|---|---|
| error | Error | The error object representing the serialization error. |
| [options] | SerializationErrorOptions | Error-handling options (optional). |
Example
try {
// Code that may throw a serialization error
} catch (error) {
handleSerializationError(error, { logError: true, errorMessage: 'Failed to serialize data.' });
}
voidHandles deserialization errors with optional error-handling options.
Kind: global function
Throws:
Error Throws an error if the error-handling options are invalid.| Param | Type | Description |
|---|---|---|
| error | Error | The error object representing the deserialization error. |
| [options] | DeserializationErrorOptions | Error-handling options (optional). |
Example
try {
// Code that may throw a deserialization error
} catch (error) {
handleDeserializationError(error, { logError: true, errorMessage: 'Failed to deserialize data.' });
}
booleanValidates serialized data in various formats with optional validation options.
Kind: global function
Returns: boolean - Returns true if the serialized data is valid according to the specified format; otherwise, it returns false. If throwError is true and the format is unsupported or validation fails, an error is thrown. If throwError is false, errors are logged to the console, and false is returned in case of validation failure.
Throws:
Error Throws an error if the validation format is not supported or if an error occurs during validation (when throwError is true).Remarks: This function allows you to validate serialized data in various formats such as JSON, XML, or CSV. You can specify the format and validation options. By default, it throws errors on unsupported formats or validation failures, but you can customize this behavior.
| Param | Type | Description |
|---|---|---|
| serializedData | string | The serialized data to be validated. |
| format | string | The format of the serialized data (e.g., "json", "xml", "csv"). |
| [options] | ValidationOptions | Validation options (optional). |
Example
const serializedData = ...; // Serialized data to be validated
const isValid = validateSerializedData(serializedData, "json");
if (isValid) {
console.log("Data is valid.");
} else {
console.error("Data is invalid.");
}
stringStringify a JSON object with optional pretty-printing.
Kind: global function
Returns: string - The stringified JSON.
| Param | Type | Default | Description |
|---|---|---|---|
| jsonObj | any | The JSON object to stringify. | |
| prettyPrint | boolean | false | Whether to enable pretty-printing (default is false). |
Example
const json = { name: 'John', age: 30 };
const jsonString = stringifyJSON(json, true);
console.log(jsonString);
Output:
{
"name": "John",
"age": 30
}
any | nullParse a JSON string safely, handling potential parsing errors.
Kind: global function
Returns: any | null - The parsed JSON object, or null if there was an error.
| Param | Type | Description |
|---|---|---|
| jsonString | string | The JSON string to parse. |
Example
const jsonString = '{"name":"John","age":30}';
const parsedJSON = parseJSON(jsonString);
if (parsedJSON !== null) {
console.log(parsedJSON.name); // Output: John
}
anyDeep clone a JSON object to prevent reference sharing.
Kind: global function
Returns: any - The deep-cloned JSON object.
| Param | Type | Description |
|---|---|---|
| jsonObj | any | The JSON object to clone. |
Example
const originalJSON = { name: 'John', age: 30 };
const clonedJSON = deepCloneJSON(originalJSON);
console.log(clonedJSON.name); // Output: John
anyMerge two JSON objects into a new one.
Kind: global function
Returns: any - The merged JSON object.
| Param | Type | Description |
|---|---|---|
| obj1 | any | The first JSON object to merge. |
| obj2 | any | The second JSON object to merge. |
Example
const obj1 = { name: 'John' };
const obj2 = { age: 30 };
const mergedObject = mergeJSONObjects(obj1, obj2);
console.log(mergedObject.name); // Output: John
console.log(mergedObject.age); // Output: 30
Record.<string, any>Filter a JSON object based on a callback function.
Kind: global function
Returns: Record.<string, any> - The filtered JSON object.
| Param | Type | Description |
|---|---|---|
| jsonObj | Record.<string, any> | The JSON object to filter. |
| filterFn | function | The filter callback function. |
Example
const data = { name: 'John', age: 30, city: 'New York' };
const filteredData = filterJSONObject(data, (key, value) => key !== 'city');
console.log(filteredData.city); // Output: undefined
Record.<string, any>Map the values of a JSON object using a callback function.
Kind: global function
Returns: Record.<string, any> - The mapped JSON object.
| Param | Type | Description |
|---|---|---|
| jsonObj | Record.<string, any> | The JSON object to map. |
| mapFn | function | The mapping callback function. |
Example
const data = { count: 5, price: 10 };
const mappedData = mapJSONObjectValues(data, (value) => value * 2);
console.log(mappedData.count); // Output: 10
console.log(mappedData.price); // Output: 20
stringConvert a JSON object into URL query parameters.
Kind: global function
Returns: string - The URL query string.
| Param | Type | Description |
|---|---|---|
| jsonObj | Record.<string, any> | The JSON object to convert. |
Example
const queryParams = { name: 'John', age: 30 };
const queryString = jsonToQueryString(queryParams);
console.log(queryString); // Output: "name=John&age=30"
Array.<string>Extract keys from a JSON object.
Kind: global function
Returns: Array.<string> - An array of keys from the JSON object.
| Param | Type | Description |
|---|---|---|
| jsonObj | Record.<string, any> | The JSON object to extract keys from. |
Example
const data = { name: 'John', age: 30 };
const keys = extractKeysFromJSON(data);
console.log(keys); // Output: ["name", "age"]
booleanCheck if a JSON object is empty (contains no key-value pairs).
Kind: global function
Returns: boolean - True if the JSON object is empty, otherwise false.
| Param | Type | Description |
|---|---|---|
| jsonObj | Record.<string, any> | The JSON object to check. |
Example
const emptyObj = {};
const nonEmptyObj = { name: 'John' };
console.log(isJSONObjectEmpty(emptyObj)); // Output: true
console.log(isJSONObjectEmpty(nonEmptyObj)); // Output: false
any | undefinedGet the value of a nested key within a JSON object using a dot-separated path.
Kind: global function
Returns: any | undefined - The value of the nested key, or undefined if not found.
| Param | Type | Description |
|---|---|---|
| jsonObj | Record.<string, any> | The JSON object to search within. |
| path | string | The dot-separated path to the nested key. |
Example
const data = { person: { name: 'John', age: 30 } };
const nestedValue = getNestedValue(data, 'person.name');
console.log(nestedValue); // Output: "John"
Array.<any>Convert a JSON object into an array of its values.
Kind: global function
Returns: Array.<any> - An array containing the values from the JSON object.
| Param | Type | Description |
|---|---|---|
| jsonObj | Record.<string, any> | The JSON object to convert. |
Example
const data = { name: 'John', age: 30 };
const valuesArray = jsonToArray(data);
console.log(valuesArray); // Output: ["John", 30]
Record.<string, any>Convert an array of objects into a JSON object using a specified key from each object.
Kind: global function
Returns: Record.<string, any> - The JSON object created from the array.
| Param | Type | Description |
|---|---|---|
| arr | Array.<any> | The array of objects to convert. |
| keyName | string | The key name to use from each object as the key in the resulting JSON object. |
Example
const dataArray = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
];
const jsonObject = arrayToJSONObject(dataArray, 'id');
console.log(jsonObject);
Output:
{
"1": { "id": 1, "name": "John" },
"2": { "id": 2, "name": "Jane" }
}
Record.<string, any>Remove a key from a JSON object.
Kind: global function
Returns: Record.<string, any> - A new JSON object with the specified key removed.
| Param | Type | Description |
|---|---|---|
| jsonObj | Record.<string, any> | The JSON object from which to remove the key. |
| keyToRemove | string | The key to remove from the JSON object. |
Example
const data = { name: 'John', age: 30 };
const newData = removeKeyFromJSON(data, 'age');
console.log(newData.age); // Output: undefined
Asserts that two values are equal using strict equality (===).
Kind: global function
Throws:
Error Throws an error if the actual and expected values are not equal.| Param | Type | Description |
|---|---|---|
| actual | T | The actual value to compare. |
| expected | T | The expected value for comparison. |
Example
assertEqual(5, 5); // No error is thrown
assertEqual("Hello", "World"); // Error: Values are not equal
Asserts that two values are not equal using strict inequality (!==).
Kind: global function
Throws:
Error Throws an error if the actual and notExpected values are equal.| Param | Type | Description |
|---|---|---|
| actual | T | The actual value to compare. |
| notExpected | T | The value that should not be equal to the actual value. |
Example
assertNotEqual(5, 10); // No error is thrown
assertNotEqual("Hello", "Hello"); // Error: Values are equal
Asserts that a given expression evaluates to true.
Kind: global function
Throws:
Error Throws an error if the expression evaluates to false.| Param | Type | Description |
|---|---|---|
| expression | boolean | The expression to evaluate. |
| message | string | An optional message to include in the error if the assertion fails. |
Example
const x = 5;
assertTrue(x === 5, "x should be equal to 5"); // No error is thrown
assertTrue(x > 10, "x should be greater than 10"); // Error: x should be greater than 10
Asserts that a given function raises an exception when called.
Kind: global function
Throws:
Error Throws an error if the function does not raise the expected exception or if it doesn't raise an exception at all.| Param | Type | Description |
|---|---|---|
| func | function | The function to be tested for raising an exception. |
| [expectedError] | ErrorConstructor | The expected error constructor to check against. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}
assertRaises(() => divide(10, 0), Error, "Division by zero"); // No error is thrown
assertRaises(() => divide(10, 2), Error, "Division by zero"); // Error: Expected an error but no error was raised
Asserts that a given function does not raise an exception when called.
Kind: global function
Throws:
Error Throws an error if the function raises any exception.| Param | Type | Description |
|---|---|---|
| func | function | The function to be tested for not raising an exception. |
Example
function safeDivide(a, b) {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}
assertNoRaises(() => safeDivide(10, 2)); // No error is thrown
assertNoRaises(() => safeDivide(10, 0)); // Error: Expected no error but an error was raised
Asserts that an iterable (e.g., an array or string) contains a specified element.
Kind: global function
Throws:
Error Throws an error if the element is not found in the iterable.| Param | Type | Description |
|---|---|---|
| iterable | Iterable.<T> | The iterable to search for the element. |
| element | T | The element to check for in the iterable. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
const numbers = [1, 2, 3, 4, 5];
assertContains(numbers, 3); // No error is thrown
assertContains(numbers, 6); // Error: Element 6 is not found in the iterable
Asserts that an iterable (e.g., an array or string) does not contain a specified element.
Kind: global function
Throws:
Error Throws an error if the element is found in the iterable.| Param | Type | Description |
|---|---|---|
| iterable | Iterable.<T> | The iterable to search for the element. |
| element | T | The element to check for absence in the iterable. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
const numbers = [1, 2, 3, 4, 5];
assertNotContains(numbers, 6); // No error is thrown
assertNotContains(numbers, 3); // Error: Element 3 is found in the iterable
Asserts that one iterable is a subset of another iterable.
Kind: global function
Throws:
Error Throws an error if the subset is not found in the superset.| Param | Type | Description |
|---|---|---|
| subset | Iterable.<T> | The iterable that should be a subset. |
| superset | Iterable.<T> | The iterable that should contain the subset. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3]);
assertSubset(set2, set1); // No error is thrown
assertSubset(set1, set2); // Error: Not a subset
Asserts that two numbers are almost equal within a specified tolerance.
Kind: global function
Throws:
Error Throws an error if the numbers are not almost equal within the tolerance.| Param | Type | Default | Description |
|---|---|---|---|
| actual | number | The actual number to compare. | |
| expected | number | The expected number for comparison. | |
| [tolerance] | number | 1e-9 | The tolerance within which the numbers are considered equal. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertAlmostEqual(0.1 + 0.2, 0.3); // No error is thrown
assertAlmostEqual(0.1 + 0.2, 0.3, 1e-6); // No error is thrown
assertAlmostEqual(0.1 + 0.2, 0.3, 1e-10); // Error: Numbers are not almost equal
Asserts that a number is greater than another number.
Kind: global function
Throws:
Error Throws an error if the actual number is not greater than the expected number.| Param | Type | Description |
|---|---|---|
| actual | number | The actual number to compare. |
| expected | number | The expected number for comparison. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertGreaterThan(5, 3); // No error is thrown
assertGreaterThan(3, 5); // Error: Expected greater than 5, but got 3
Asserts that a number is less than another number.
Kind: global function
Throws:
Error Throws an error if the actual number is not less than the expected number.| Param | Type | Description |
|---|---|---|
| actual | number | The actual number to compare. |
| expected | number | The expected number for comparison. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertLessThan(3, 5); // No error is thrown
assertLessThan(5, 3); // Error: Expected less than 3, but got 5
Asserts that a string contains a specified substring.
Kind: global function
Throws:
Error Throws an error if the actual string does not contain the expected substring.| Param | Type | Description |
|---|---|---|
| actual | string | The actual string to check. |
| expectedSubstring | string | The substring that should be contained in the actual string. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertStringContains("Hello, World!", "World"); // No error is thrown
assertStringContains("Hello, World!", "Universe"); // Error: String does not contain "Universe"
Asserts that a string starts with a specified prefix.
Kind: global function
Throws:
Error Throws an error if the actual string does not start with the expected prefix.| Param | Type | Description |
|---|---|---|
| actual | string | The actual string to check. |
| expectedPrefix | string | The prefix that should be at the beginning of the actual string. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertStringStartsWith("Hello, World!", "Hello"); // No error is thrown
assertStringStartsWith("Hello, World!", "Hi"); // Error: String does not start with "Hi"
Asserts that a string ends with a specified suffix.
Kind: global function
Throws:
Error Throws an error if the actual string does not end with the expected suffix.| Param | Type | Description |
|---|---|---|
| actual | string | The actual string to check. |
| expectedSuffix | string | The suffix that should be at the end of the actual string. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertStringEndsWith("Hello, World!", "World!"); // No error is thrown
assertStringEndsWith("Hello, World!", "Universe"); // Error: String does not end with "Universe"
Asserts that a file exists at the specified path.
Kind: global function
Throws:
Error Throws an error if no file exists at the specified path.| Param | Type | Description |
|---|---|---|
| path | string | The path to the file to check. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertFileExists("/path/to/myfile.txt"); // No error is thrown
assertFileExists("/nonexistentfile.txt"); // Error: File does not exist at "/nonexistentfile.txt"
Ensures that no file exists at the specified path.
Kind: global function
Throws:
Error Throws an error if a file exists at the specified path.| Param | Type | Description |
|---|---|---|
| path | string | The path to the file to check for non-existence. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertFileNotExists("/path/to/nonexistentfile.txt"); // No error is thrown
assertFileNotExists("/path/to/myfile.txt"); // Error: File exists at "/path/to/myfile.txt"
Array.<any>Generates a sample dataset of the specified size for testing purposes.
Kind: global function
Returns: Array.<any> - An array containing the generated test data.
| Param | Type | Description |
|---|---|---|
| size | number | The size of the dataset to generate. |
Example
const testData = generateTestData(100); // Generates an array of 100 test data items.
Checks if the mock function was called with specific arguments.
Kind: global function
Throws:
Error Throws an error if the mock function was not called with the expected arguments.| Param | Type | Description |
|---|---|---|
| mockFunction | function | The mock function to check. |
| ...args | any | The arguments to check against the mock function's call. |
Example
const mockFunc = mockFunction(() => {});
mockFunc(1, "abc");
assertCalledWith(mockFunc, 1, "abc"); // No error is thrown
assertCalledWith(mockFunc, 2, "xyz"); // Error: Mock function was not called with (2, "xyz")
The flag to track whether the mock function was called with the expected arguments.
Kind: inner property of assertCalledWith
numberMeasures and logs the execution time of a function.
Kind: global function
Returns: number - The execution time of the function in milliseconds.
| Param | Type | Description |
|---|---|---|
| func | function | The function to measure the execution time of. |
| ...args | any | The arguments to pass to the function when calling it. |
Example
const executionTime = measureExecutionTime(() => {
// Code to measure execution time
for (let i = 0; i < 1000000; i++) {
// Some computation
}
});
console.log(`Execution time: ${executionTime} ms`);
Ensures that a function executes in less than a specified max_time.
Kind: global function
Throws:
Error Throws an error if the function execution time exceeds max_time.| Param | Type | Description |
|---|---|---|
| func | function | The function to be executed and timed. |
| maxTime | number | The maximum allowed execution time in milliseconds. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertExecutionTimeLessThan(() => {
// Code to test performance
for (let i = 0; i < 1000000; i++) {
// Some computation
}
}, 100); // No error is thrown
assertExecutionTimeLessThan(() => {
// Code to test performance
for (let i = 0; i < 1000000; i++) {
// Some slow computation
}
}, 10); // Error: Execution time exceeded 10 ms
Sends an HTTP request to a URL and checks if the response status code matches the expected code.
Kind: global function
Throws:
Error Throws an error if the response status code does not match the expected code.| Param | Type | Description |
|---|---|---|
| url | string | The URL to send the HTTP request to. |
| expectedStatusCode | number | The expected HTTP status code to compare with the response. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertHttpStatus("https://example.com/api/data", 200); // No error is thrown if status code is 200
assertHttpStatus("https://example.com/api/data", 404, "API endpoint should return 404"); // Error: API endpoint should return 404
Retrieves a web page from a URL and verifies that it contains the expected content.
Kind: global function
Throws:
Error Throws an error if the web page does not contain the expected content.| Param | Type | Description |
|---|---|---|
| url | string | The URL to retrieve the web page from. |
| expectedContent | string | The expected content that should be found in the web page. |
| [message] | string | An optional message to include in the error if the assertion fails. |
Example
assertWebPageContains("https://example.com", "Welcome to Example"); // No error is thrown if the content is found
assertWebPageContains("https://example.com", "Nonexistent Content", "Web page should contain 'Nonexistent Content'"); // Error: Web page should contain 'Nonexistent Content'
Array.<any>Generates random data of a specified type and size for testing.
Kind: global function
Returns: Array.<any> - An array containing the generated random data.
| Param | Type | Description |
|---|---|---|
| dataType | string | The type of random data to generate (e.g., 'string', 'number', 'boolean'). |
| size | number | The size of the random data to generate. |
Example
const randomStrings = generateRandomData('string', 10); // Generates an array of 10 random strings
const randomNumbers = generateRandomData('number', 5); // Generates an array of 5 random numbers
const randomBooleans = generateRandomData('boolean', 7); // Generates an array of 7 random booleans
booleanCompares two data structures for equality, ignoring minor differences.
Kind: global function
Returns: boolean - true if the data structures are considered equal; otherwise, false.
| Param | Type | Default | Description |
|---|---|---|---|
| actual | any | The actual data structure to compare. | |
| expected | any | The expected data structure to compare against. | |
| [tolerance] | number | 1e-6 | A numerical tolerance for comparing floating-point numbers. |
Example
const actualArray = [1.0, 2.0, 3.0];
const expectedArray = [1.000001, 2.000002, 3.000003];
const result = compareData(actualArray, expectedArray); // Returns true with default tolerance
const actualObject = { value: 0.1 + 0.2 };
const expectedObject = { value: 0.3 };
const result = compareData(actualObject, expectedObject, 1e-6); // Returns true
anyCleans a data structure by removing specified elements.
Kind: global function
Returns: any - The cleaned data structure with specified elements removed.
| Param | Type | Description |
|---|---|---|
| data | any | The data structure to clean. |
| elementsToRemove | Array.<any> | An array of elements to remove from the data structure. |
Example
const data = [1, 2, 3, 4, 5];
const cleanedData = cleanData(data, [2, 4]);
// cleanedData will be [1, 3, 5], removing elements 2 and 4
const objectData = { name: 'John', age: 30, address: '123 Main St' };
const cleanedObjectData = cleanData(objectData, ['age']);
// cleanedObjectData will be { name: 'John', address: '123 Main St' }, removing the 'age' property
Promise.<void>Executes a set of asynchronous operations concurrently and waits for all of them to complete.
Kind: global function
Returns: Promise.<void> - A promise that resolves when all operations have completed.
| Param | Type | Description |
|---|---|---|
| operations | Array | An array of functions that represent asynchronous operations. |
Example
const operation1 = async () => {
// Perform some asynchronous operation
await someAsyncFunction();
};
const operation2 = async () => {
// Perform another asynchronous operation
await anotherAsyncFunction();
};
await testConcurrentOperations([operation1, operation2]);
Promise.<void>Checks if a network connection can be established to a specific host and port.
Kind: global function
Returns: Promise.<void> - A promise that resolves if the network connection is successful, otherwise rejects with an error.
| Param | Type | Description |
|---|---|---|
| host | string | The host to connect to (e.g., a domain or IP address). |
| port | number | The port to use for the network connection. |
Example
try {
await assertNetworkConnection('example.com', 80);
console.log('Network connection is successful.');
} catch (error) {
console.error('Network connection failed:', error.message);
}
Promise.<void>Simulates a network failure to test error handling.
Kind: global function
Returns: Promise.<void> - A promise that rejects with an error simulating a network failure.
| Param | Type | Description |
|---|---|---|
| host | string | The host to simulate a network failure for (e.g., a domain or IP address). |
| port | number | The port to use for simulating the network failure. |
Example
try {
await simulateNetworkFailure('example.com', 80);
console.log('Network failure simulation completed.');
} catch (error) {
console.error('Simulated network failure:', error.message);
}
Promise.<Array.<any>>Runs multiple functions in parallel and collects their results for testing concurrency.
Kind: global function
Returns: Promise.<Array.<any>> - A promise that resolves with an array of results from the parallel functions.
| Param | Type | Description |
|---|---|---|
| functions | Array | An array of functions to run in parallel. |
Example
const asyncFunction1 = async () => {
// Perform some asynchronous operation
await someAsyncOperation();
return 'Result 1';
};
const asyncFunction2 = async () => {
// Perform another asynchronous operation
await anotherAsyncOperation();
return 'Result 2';
};
const results = await testParallelFunctions([asyncFunction1, asyncFunction2]);
// results will be an array containing the results of asyncFunction1 and asyncFunction2.
URL | undefinedGenerates a URL object from a given string address.
Kind: global function
Returns: URL | undefined - A URL object if the address is valid, or undefined if it's not.
Remarks: This function attempts to create a URL object from the given address using the URL constructor. If the address is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
| base | string | The base URL for resolving relative URLs (optional). |
Example
Example 1:
const result1: URL | undefined = generateURL("https://www.example.com");
Example 2:
const result2: URL | undefined = generateURL("invalid-url");
string | undefinedExtracts the hash portion of a URL.
Kind: global function
Returns: string | undefined - The hash portion of the URL, or undefined if the URL is invalid.
Remarks: This function attempts to extract the hash portion of a URL using the URL constructor. If the URL is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlHash("https://www.example.com/#section1");
Returns "#section1"
Example 2:
const result2: string | undefined = urlHash("invalid-url");
Returns undefined
string | undefinedExtracts the host (domain) portion of a URL.
Kind: global function
Returns: string | undefined - The host portion of the URL, or undefined if the URL is invalid.
Remarks: This function attempts to extract the host (domain) portion of a URL using the URL constructor. If the URL is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlHost("https://www.example.com/path/to/page");
Returns "www.example.com"
Example 2:
const result2: string | undefined = urlHost("invalid-url");
Returns undefined
string | undefinedRetrieves the full URL from a given string address.
Kind: global function
Returns: string | undefined - The full URL, or undefined if the URL is invalid.
Remarks: This function attempts to retrieve the full URL from the given string address using the URL constructor. If the URL is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlHref("https://www.example.com/path/to/page");
Returns "https://www.example.com/path/to/page"
Example 2:
const result2: string | undefined = urlHref("invalid-url");
Returns undefined
string | undefinedRetrieves the origin of a URL from a given string address.
Kind: global function
Returns: string | undefined - The origin of the URL, or undefined if the URL is invalid.
Remarks: This function attempts to retrieve the origin of a URL from the given string address using the URL constructor. If the URL is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlOrigin("https://www.example.com/path/to/page");
Returns "https://www.example.com"
Example 2:
const result2: string | undefined = urlOrigin("invalid-url");
Returns undefined
string | undefinedRetrieves the password portion of a URL from a given string address.
Kind: global function
Returns: string | undefined - The password portion of the URL, or undefined if the URL is invalid or doesn't contain a password.
Remarks: This function attempts to retrieve the password portion of a URL from the given string address using the URL constructor. If the URL is invalid or doesn't contain a password, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlPassword("https://user:password@example.com");
Returns "password"
Example 2:
const result2: string | undefined = urlPassword("https://www.example.com");
Returns undefined
string | undefinedRetrieves the pathname portion of a URL from a given string address.
Kind: global function
Returns: string | undefined - The pathname portion of the URL, or undefined if the URL is invalid.
Remarks: This function attempts to retrieve the pathname portion of a URL from the given string address using the URL constructor. If the URL is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlPathname("https://www.example.com/path/to/page");
Returns "/path/to/page"
Example 2:
const result2: string | undefined = urlPathname("invalid-url");
Returns undefined
string | undefinedRetrieves the port portion of a URL from a given string address.
Kind: global function
Returns: string | undefined - The port portion of the URL, or undefined if the URL is invalid or doesn't contain a port.
Remarks: This function attempts to retrieve the port portion of a URL from the given string address using the URL constructor. If the URL is invalid or doesn't contain a port, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlPort("https://www.example.com:8080/path/to/page");
Returns "8080"
Example 2:
const result2: string | undefined = urlPort("https://www.example.com/path/to/page");
Returns undefined
string | undefinedRetrieves the protocol portion of a URL from a given string address.
Kind: global function
Returns: string | undefined - The protocol portion of the URL, or undefined if the URL is invalid.
Remarks: This function attempts to retrieve the protocol portion of a URL from the given string address using the URL constructor. If the URL is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlProtocol("https://www.example.com/path/to/page");
Returns "https:"
Example 2:
const result2: string | undefined = urlProtocol("invalid-url");
Returns undefined
string | undefinedRetrieves the search/query portion of a URL from a given string address.
Kind: global function
Returns: string | undefined - The search/query portion of the URL, or undefined if the URL is invalid.
Remarks: This function attempts to retrieve the search/query portion of a URL from the given string address using the URL constructor. If the URL is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlSearch("https://www.example.com/search?query=example");
Returns "?query=example"
Example 2:
const result2: string | undefined = urlSearch("invalid-url");
Returns undefined
string | null | undefinedRetrieves the value of a query parameter from the search/query portion of a URL.
Kind: global function
Returns: string | null | undefined - The value of the query parameter, null if the parameter is not found, or undefined if the URL is invalid.
Remarks: This function attempts to retrieve the value of a query parameter from the search/query portion of a URL using the URL constructor and the URLSearchParams API. If the URL is invalid, it returns undefined. If the parameter is not found, it returns null.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
| param | string | The name of the query parameter to retrieve. |
Example
Example 1:
const result1: string | null | undefined = urlSearchParams("https://www.example.com/search?query=example", "query");
Returns "example"
Example 2:
const result2: string | null | undefined = urlSearchParams("https://www.example.com/search?query=example", "page");
Returns null (parameter not found)
Example 3:
const result3: string | null | undefined = urlSearchParams("invalid-url", "param");
Returns undefined (invalid URL)
string | undefinedRetrieves the username portion of a URL from a given string address.
Kind: global function
Returns: string | undefined - The username portion of the URL, or undefined if the URL is invalid or doesn't contain a username.
Remarks: This function attempts to retrieve the username portion of a URL from the given string address using the URL constructor. If the URL is invalid or doesn't contain a username, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = urlUsername("https://user:password@example.com/path/to/page");
Returns "user"
Example 2:
const result2: string | undefined = urlUsername("https://www.example.com/path/to/page");
Returns undefined
string | undefinedCreates a DOMString containing a URL representing the given file object.
Kind: global function
Returns: string | undefined - A DOMString containing the URL representing the file, or undefined if an error occurs.
Remarks: This function creates a URL representing the given file object using the URL.createObjectURL method. If an error occurs, it returns undefined.
| Param | Type | Description |
|---|---|---|
| file | File | The File or Blob object for which to create a URL. |
Example
Example 1:
const file = new File(['file content'], 'example.txt', { type: 'text/plain' });
const result1: string | undefined = createObjectURL(file);
Returns a URL representing the file content.
Example 2:
const result2: string | undefined = createObjectURL(null);
Returns undefined (invalid input)
voidRevokes a previously created object URL, releasing associated resources.
Kind: global function
Remarks: This function revokes a previously created object URL using the URL.revokeObjectURL method. If an error occurs, it will not be caught within this function.
| Param | Type | Description |
|---|---|---|
| url | string | The object URL to revoke. |
Example
Example:
const objectUrl = createObjectURL(someFile);
revokeObjectURL(objectUrl);
string | undefinedConverts a URL string to a JSON representation.
Kind: global function
Returns: string | undefined - A JSON representation of the URL, or undefined if the URL is invalid.
Remarks: This function attempts to convert a URL string to a JSON representation using the URL constructor's toJSON method. If the URL is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = url2JSON("https://www.example.com/path/to/page");
Returns '{"href":"https://www.example.com/path/to/page","origin":"https://www.example.com",...}'
Example 2:
const result2: string | undefined = url2JSON("invalid-url");
Returns undefined
string | undefinedConverts a URL string to a string representation.
Kind: global function
Returns: string | undefined - A string representation of the URL, or undefined if the URL is invalid.
Remarks: This function attempts to convert a URL string to a string representation using the URL constructor's toString method. If the URL is invalid, it returns undefined.
| Param | Type | Description |
|---|---|---|
| address | string | The string representing the URL address. |
Example
Example 1:
const result1: string | undefined = url2String("https://www.example.com/path/to/page");
Returns "https://www.example.com/path/to/page"
Example 2:
const result2: string | undefined = url2String("invalid-url");
Returns undefined
booleanChecks if a given string is a valid email address.
Kind: global function
Returns: boolean - true if the email is valid, false otherwise.
Remarks: This function uses a regular expression to check if the provided string matches the pattern of a valid email address. It returns true if the email is valid and false otherwise.
| Param | Type | Description |
|---|---|---|
string | The string to validate as an email address. |
Example
Example 1:
const result1: boolean = isValidEmail("test@example.com");
Returns true
Example 2:
const result2: boolean = isValidEmail("invalid-email");
Returns false
booleanChecks if a given password meets specific criteria.
Kind: global function
Returns: boolean - true if the password meets the criteria, false otherwise.
Remarks: This function checks if the provided password meets the specified criteria, including the presence of uppercase letters, lowercase letters, digits, special characters, and a minimum length (default is 8 characters).
| Param | Type | Default | Description |
|---|---|---|---|
| password | string | The password to validate. | |
| upper | boolean | true | Whether the password must contain an uppercase letter. |
| lower | boolean | true | Whether the password must contain a lowercase letter. |
| num | boolean | true | Whether the password must contain a digit. |
| special | boolean | true | Whether the password must contain a special character. |
| length | boolean | true | Whether the password must have a length of at least 8 characters. |
Example
Example 1:
const result1: boolean = isValidPassword("P@ssw0rd");
Returns true
Example 2:
const result2: boolean = isValidPassword("weak");
Returns false
booleanChecks if a given string is a valid phone number.
Kind: global function
Returns: boolean - true if the phone number is valid, false otherwise.
Remarks: This function checks if the provided string is a valid phone number. It allows both 10-digit numeric phone numbers and numeric phone numbers with a leading plus sign (e.g., "+1234567890").
| Param | Type | Description |
|---|---|---|
| phone | string | The string to validate as a phone number. |
Example
Example 1:
const result1: boolean = isValidPhone("1234567890");
Returns true
Example 2:
const result2: boolean = isValidPhone("+1234567890");
Returns true
Example 3:
const result3: boolean = isValidPhone("invalid-phone");
Returns false
booleanChecks if a given string is a valid URL.
Kind: global function
Returns: boolean - true if the URL is valid, false otherwise.
Remarks: This function uses regular expressions to check if the provided string matches the pattern of a valid URL. It also takes an optional base URL for relative URL validation.
| Param | Type | Description |
|---|---|---|
| address | string | The string to validate as a URL. |
| base | string | The optional base URL to use for relative URL validation. |
Example
Example 1:
const result1: boolean = isValidUrl("https://www.example.com");
Returns true
Example 2:
const result2: boolean = isValidUrl("invalid-url");
Returns false
booleanChecks if a given string is a valid username.
Kind: global function
Returns: boolean - true if the username is valid, false otherwise.
Remarks: This function uses a regular expression to check if the provided string contains only alphanumeric characters and underscores, which are typically allowed in usernames.
| Param | Type | Description |
|---|---|---|
| username | string | The string to validate as a username. |
Example
Example 1:
const result1: boolean = isValidUsername("user123");
Returns true
Example 2:
const result2: boolean = isValidUsername("user-name");
Returns false
booleanChecks if a given number is an integer.
Kind: global function
Returns: boolean - true if the number is an integer, false otherwise.
Remarks: This function checks if the provided number is an integer by verifying if its remainder when divided by 1 is equal to 0.
| Param | Type | Description |
|---|---|---|
| num | number | The number to check. |
Example
Example 1:
const result1: boolean = isInteger(42);
Returns true
Example 2:
const result2: boolean = isInteger(3.14);
Returns false
booleanChecks if a given number is finite (neither Infinity nor NaN).
Kind: global function
Returns: boolean - true if the number is finite, false otherwise.
Remarks: This function checks if the provided number is finite using the Number.isFinite method.
| Param | Type | Description |
|---|---|---|
| num | number | The number to check. |
Example
Example 1:
const result1: boolean = isFinite(42);
Returns true
Example 2:
const result2: boolean = isFinite(Infinity);
Returns false
booleanChecks if a given number is NaN (Not-a-Number).
Kind: global function
Returns: boolean - true if the number is NaN, false otherwise.
Remarks: This function checks if the provided number is NaN using the Number.isNaN method.
| Param | Type | Description |
|---|---|---|
| num | number | The number to check. |
Example
Example 1:
const result1: boolean = isNaN(NaN);
Returns true
Example 2:
const result2: boolean = isNaN(42);
Returns false
booleanChecks if a given number is a safe integer.
Kind: global function
Returns: boolean - true if the number is a safe integer, false otherwise.
Remarks: This function checks if the provided number is a safe integer using the Number.isSafeInteger method.
| Param | Type | Description |
|---|---|---|
| num | number | The number to check. |
Example
Example 1:
const result1: boolean = isSafeInteger(42);
Returns true
Example 2:
const result2: boolean = isSafeInteger(2 ** 53);
Returns false
booleanChecks if a given value is a string.
Kind: global function
Returns: boolean - true if the value is a string, false otherwise.
Remarks: This function checks if the provided value is a string by comparing its type to "string".
| Param | Type | Description |
|---|---|---|
| value | string | The value to check. |
Example
Example 1:
const result1: boolean = isString("Hello, World!");
Returns true
Example 2:
const result2: boolean = isString(42);
Returns false
booleanChecks if a given number is a decimal (not an integer).
Kind: global function
Returns: boolean - true if the number is a decimal, false otherwise.
Remarks: This function checks if the provided number is a decimal (not an integer) by verifying if its remainder when divided by 1 is not equal to 0.
| Param | Type | Description |
|---|---|---|
| num | number | The number to check. |
Example
Example 1:
const result1: boolean = isDecimal(3.14);
Returns true
Example 2:
const result2: boolean = isDecimal(42);
Returns false
booleanChecks if a given value is a boolean.
Kind: global function
Returns: boolean - true if the value is a boolean, false otherwise.
Remarks: This function checks if the provided value is a boolean by comparing it to true or false.
| Param | Type | Description |
|---|---|---|
| value | boolean | The value to check. |
Example
Example 1:
const result1: boolean = isBoolean(true);
Returns true
Example 2:
const result2: boolean = isBoolean("false");
Returns false
booleanChecks if a given string is in uppercase.
Kind: global function
Returns: boolean - true if the string is in uppercase, false otherwise.
Remarks: This function checks if the provided string is in uppercase by comparing it to its uppercase version.
| Param | Type | Description |
|---|---|---|
| text | string | The string to check. |
Example
Example 1:
const result1: boolean = isUpperCase("HELLO");
Returns true
Example 2:
const result2: boolean = isUpperCase("Hello");
Returns false
booleanChecks if a given string is in lowercase.
Kind: global function
Returns: boolean - true if the string is in lowercase, false otherwise.
Remarks: This function checks if the provided string is in lowercase by comparing it to its lowercase version.
| Param | Type | Description |
|---|---|---|
| text | string | The string to check. |
Example
Example 1:
const result1: boolean = isLowerCase("hello");
Returns true
Example 2:
const result2: boolean = isLowerCase("Hello");
Returns false
booleanChecks if a given string contains only alphabetic characters (A-Z, a-z).
Kind: global function
Returns: boolean - true if the string contains only alphabetic characters, false otherwise.
Remarks: This function uses a regular expression to check if the provided string contains only alphabetic characters.
| Param | Type | Description |
|---|---|---|
| text | string | The string to check. |
Example
Example 1:
const result1: boolean = isAlpha("abcXYZ");
Returns true
Example 2:
const result2: boolean = isAlpha("Hello123");
Returns false
booleanChecks if a given string contains only numeric characters (0-9).
Kind: global function
Returns: boolean - true if the string contains only numeric characters, false otherwise.
Remarks: This function uses a regular expression to check if the provided string contains only numeric characters.
| Param | Type | Description |
|---|---|---|
| text | string | The string to check. |
Example
Example 1:
const result1: boolean = isNumeric("12345");
Returns true
Example 2:
const result2: boolean = isNumeric("42a");
Returns false
booleanChecks if a given string contains only alphanumeric characters (A-Z, a-z, 0-9).
Kind: global function
Returns: boolean - true if the string contains only alphanumeric characters, false otherwise.
Remarks: This function uses a regular expression to check if the provided string contains only alphanumeric characters.
| Param | Type | Description |
|---|---|---|
| text | string | The string to check. |
Example
Example 1:
const result1: boolean = isAlphaNumeric("Hello123");
Returns true
Example 2:
const result2: boolean = isAlphaNumeric("Hello@123");
Returns false
booleanChecks if a given string is strictly alphanumeric, containing at least one alphabetic character (A-Z, a-z) and one numeric character (0-9).
Kind: global function
Returns: boolean - true if the string is strictly alphanumeric, false otherwise.
Remarks: This function first checks if the provided string is alphanumeric using the isAlphaNumeric function. If it is, it further checks if the string contains at least one alphabetic character and one numeric character.
| Param | Type | Description |
|---|---|---|
| text | string | The string to check. |
Example
Example 1:
const result1: boolean = isStrictAlphaNumeric("Hello123");
Returns true
Example 2:
const result2: boolean = isStrictAlphaNumeric("123");
Returns false
booleanChecks if a given string is in CamelCase.
Kind: global function
Returns: boolean - true if the string is in CamelCase, false otherwise.
Remarks: This function uses a regular expression to check if the provided string is in CamelCase format.
| Param | Type | Description |
|---|---|---|
| text | string | The string to check. |
Example
Example 1:
const result1: boolean = isCamelCase("helloWorld");
Returns true
Example 2:
const result2: boolean = isCamelCase("hello_world");
Returns false
booleanChecks if a given string is in PascalCase.
Kind: global function
Returns: boolean - true if the string is in PascalCase, false otherwise.
Remarks: This function uses a regular expression to check if the provided string is in PascalCase format.
| Param | Type | Description |
|---|---|---|
| text | string | The string to check. |
Example
Example 1:
const result1: boolean = isPascalCase("HelloWorld");
Returns true
Example 2:
const result2: boolean = isPascalCase("helloWorld");
Returns false
booleanChecks if a given string is in snake_case.
Kind: global function
Returns: boolean - true if the string is in snake_case, false otherwise.
Remarks: This function uses a regular expression to check if the provided string is in snake_case format.
| Param | Type | Description |
|---|---|---|
| text | string | The string to check. |
Example
Example 1:
const result1: boolean = isSnakeCase("hello_world");
Returns true
Example 2:
const result2: boolean = isSnakeCase("HelloWorld");
Returns false
booleanChecks if a date of birth is in a valid format and within an acceptable range.
Kind: global function
Returns: boolean - True if the date of birth is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| dateOfBirth | string | The date of birth to validate (yyyy-mm-dd format). |
Example
const isValid = isDateOfBirthValid("1990-01-15"); // Returns true
booleanChecks if a postal code matches the format for a specific country or region.
Kind: global function
Returns: boolean - True if the postal code is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| postalCode | string | The postal code to validate. |
Example
const isValid = isPostalCodeValid("12345"); // Returns true
booleanChecks if a credit card number passes basic validation (e.g., checksum).
Kind: global function
Returns: boolean - True if the credit card number is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| creditCardNumber | string | The credit card number to validate. |
Example
const isValid = isCreditCardValid("1234567890123456"); // Returns true
booleanChecks if a ZIP code matches a valid format for a given country or region.
Kind: global function
Returns: boolean - True if the ZIP code is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| zipCode | string | The ZIP code to validate. |
Example
const isValid = isZIPCodeValid("12345"); // Returns true
booleanChecks if a social security number (SSN) is in a valid format.
Kind: global function
Returns: boolean - True if the SSN is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| ssn | string | The social security number to validate. |
Example
const isValid = isSSNValid("123-45-6789"); // Returns true
booleanChecks if an IP address is in a valid format (IPv4 or IPv6).
Kind: global function
Returns: boolean - True if the IP address is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| ipAddress | string | The IP address to validate. |
Example
const isValid = isIPValid("192.168.0.1"); // Returns true
booleanChecks if a credit card expiration date is in the future and follows a valid format.
Kind: global function
Returns: boolean - True if the expiration date is valid and in the future, otherwise false.
| Param | Type | Description |
|---|---|---|
| expirationDate | string | The credit card expiration date to validate (MM/YYYY format). |
Example
const isValid = isCreditCardExpirationValid("12/2025"); // Returns true
booleanChecks if a security code (CVV/CVC) is valid for the specified credit card type.
Kind: global function
Returns: boolean - True if the security code is valid for the specified card type, otherwise false.
| Param | Type | Description |
|---|---|---|
| securityCode | string | The security code to validate. |
| cardType | string | The credit card type (e.g., "Visa", "MasterCard"). |
Example
const isValid = isSecurityCodeValid("123", "Visa"); // Returns true
booleanChecks if the file extension of fileName is in the list of allowed extensions.
Kind: global function
Returns: boolean - True if the file extension is allowed, otherwise false.
| Param | Type | Description |
|---|---|---|
| fileName | string | The file name to validate. |
| allowedExtensions | Array.<string> | An array of allowed file extensions (e.g., ["jpg", "png"]). |
Example
const isValid = isFileExtensionValid("document.pdf", ["pdf", "doc", "docx"]); // Returns true
booleanChecks if a one-time password (OTP) matches the expected OTP generated with the user's secret.
Kind: global function
Returns: boolean - True if the OTP is valid and matches the expected OTP, otherwise false.
| Param | Type | Description |
|---|---|---|
| otp | string | The one-time password entered by the user. |
| userSecret | string | The user's secret used for OTP generation. |
Example
const isValid = isOTPValid("123456", "secret123"); // Returns true
booleanChecks if a PIN entered by the user matches their stored PIN.
Kind: global function
Returns: boolean - True if the entered PIN matches the stored PIN, otherwise false.
| Param | Type | Description |
|---|---|---|
| pin | string | The PIN entered by the user. |
| userPin | string | The user's stored PIN. |
Example
const isValid = isPINValid("1234", "5678"); // Returns false
stringGenerates a one-time password (OTP) using the provided secret.
Kind: global function
Returns: string - The generated OTP.
| Param | Type | Description |
|---|---|---|
| secret | string | The secret used for OTP generation. |
booleanChecks if a full name follows a valid format (e.g., contains at least a first name and last name).
Kind: global function
Returns: boolean - True if the full name is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| fullName | string | The full name to validate. |
Example
const isValid = isFullNameValid("John Doe"); // Returns true
booleanChecks if an address is in a valid format (e.g., street address, city, state, postal code).
Kind: global function
Returns: boolean - True if the address is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| address | string | The address to validate. |
Example
const isValid = isAddressValid("123 Main St, New York, NY 10001"); // Returns true
booleanChecks if a city name is in a valid format (e.g., letters, no special characters).
Kind: global function
Returns: boolean - True if the city name is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| city | string | The city name to validate. |
Example
const isValid = isCityValid("New York"); // Returns true
booleanChecks if a state abbreviation or name is valid (e.g., two-letter abbreviation or full name).
Kind: global function
Returns: boolean - True if the state is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| state | string | The state abbreviation or name to validate. |
Example
const isValid = isStateValid("NY"); // Returns true
booleanChecks if an age is within the specified range.
Kind: global function
Returns: boolean - True if the age is within the specified range, otherwise false.
| Param | Type | Default | Description |
|---|---|---|---|
| age | number | The age to validate. | |
| minAge | number | 0 | The minimum allowed age. |
| maxAge | number | 120 | The maximum allowed age. |
Example
const isValid = isAgeValid(25, 18, 65); // Returns true
booleanChecks if a gender value is valid (e.g., "Male," "Female," "Other").
Kind: global function
Returns: boolean - True if the gender value is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| gender | string | The gender value to validate. |
Example
const isValid = isGenderValid("Male"); // Returns true
booleanChecks if a credit card type (e.g., "Visa," "MasterCard") is valid.
Kind: global function
Returns: boolean - True if the card type is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| cardType | string | The credit card type to validate. |
Example
const isValid = isCreditCardTypeValid("Visa"); // Returns true
booleanChecks if an International Standard Book Number (ISBN) follows a valid format.
Kind: global function
Returns: boolean - True if the ISBN is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| isbn | string | The ISBN to validate. |
Example
const isValid = isISBNValid("978-3-16-148410-0"); // Returns true
booleanChecks if a currency amount is valid (e.g., proper formatting with currency symbol).
Kind: global function
Returns: boolean - True if the currency amount is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| currencyAmount | string | The currency amount to validate. |
Example
const isValid = isCurrencyValid("$100.50"); // Returns true
booleanChecks if a time value is in a valid format (e.g., "HH:MM" or "HH:MM:SS").
Kind: global function
Returns: boolean - True if the time value is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| time | string | The time value to validate. |
Example
const isValid = isTimeValid("12:34:56"); // Returns true
booleanChecks if the URL path follows a valid format (e.g., no spaces, special characters).
Kind: global function
Returns: boolean - True if the URL path is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| urlPath | string | The URL path to validate. |
Example
const isValid = isURLPathValid("/products/category"); // Returns true
booleanChecks if the hexadecimal color code is valid (e.g., "#RRGGBB" or "#RRGGBBAA").
Kind: global function
Returns: boolean - True if the hexadecimal color code is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| hexColor | string | The hexadecimal color code to validate. |
Example
const isValid = isHexColorValid("#FFA500"); // Returns true
booleanChecks if the International Mobile Equipment Identity (IMEI) number is valid.
Kind: global function
Returns: boolean - True if the IMEI number is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| imei | string | The IMEI number to validate. |
Example
const isValid = isIMEINumberValid("123456789012345"); // Returns true
booleanChecks if the MAC address follows a valid format (e.g., "XX:XX:XX:XX:XX:XX").
Kind: global function
Returns: boolean - True if the MAC address is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| macAddress | string | The MAC address to validate. |
Example
const isValid = isMACAddressValid("00:1A:2B:3C:4D:5E"); // Returns true
booleanChecks if the domain name follows a valid format and rules (e.g., no spaces, special characters).
Kind: global function
Returns: boolean - True if the domain name is valid, otherwise false.
| Param | Type | Description |
|---|---|---|
| domainName | string | The domain name to validate. |
Example
const isValid = isDomainNameValid("example.com"); // Returns true
ObjectRepresents options for compression and decompression.
Kind: global typedef
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| [algorithm] | string | ""inflate"" | The compression or decompression algorithm to use ("inflate" or "deflate"). |
FAQs
Utility Functions for all Development Purpose
We found that wavefuel-utils demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.