New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

wavefuel-utils

Package Overview
Dependencies
Maintainers
1
Versions
58
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

wavefuel-utils

Utility Functions for all Development Purpose

latest
Source
npmnpm
Version
1.1.19
Version published
Maintainers
1
Created
Source

LinkedList

Represents a singly linked list.

Kind: global class

  • LinkedList
    • .sizenumber
    • .append(value)
    • .prepend(value)
    • .insertAfter(value, target)boolean
    • .remove(value)boolean
    • .find(value)T | null
    • .isEmpty()boolean
    • .toArray()Array.<T>
    • .clear()

linkedList.size ⇒ number

Returns 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

linkedList.append(value)

Appends a new element to the end of the linked list.

Kind: instance method of LinkedList

ParamTypeDescription
valueTThe value to append.

Example

const list = new LinkedList();
list.append(1);
list.append(2);
console.log(list.toArray()); // Output: [1, 2]

linkedList.prepend(value)

Prepends a new element to the beginning of the linked list.

Kind: instance method of LinkedList

ParamTypeDescription
valueTThe value to prepend.

Example

const list = new LinkedList();
list.prepend(1);
list.prepend(2);
console.log(list.toArray()); // Output: [2, 1]

linkedList.insertAfter(value, target) ⇒ boolean

Inserts 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.

ParamTypeDescription
valueTThe value to insert.
targetTThe 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]

linkedList.remove(value) ⇒ boolean

Removes 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.

ParamTypeDescription
valueTThe value to remove.

Example

const list = new LinkedList();
list.append(1);
list.append(2);
list.remove(1);
console.log(list.toArray()); // Output: [2]

linkedList.find(value) ⇒ T | null

Finds 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.

ParamTypeDescription
valueTThe value to find.

Example

const list = new LinkedList();
list.append(1);
list.append(2);
const foundValue = list.find(2);
console.log(foundValue); // Output: 2

linkedList.isEmpty() ⇒ boolean

Checks 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

linkedList.toArray() ⇒ 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]

linkedList.clear()

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

Stack

Represents a stack data structure.

Kind: global class

stack.push(element)

Pushes an element onto the top of the stack.

Kind: instance method of Stack

ParamTypeDescription
elementTThe element to push onto the stack.

Example

const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.toArray()); // Output: [1, 2]

stack.pop() ⇒ T | undefined

Removes 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]

stack.peek() ⇒ T | undefined

Returns 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]

stack.isEmpty() ⇒ boolean

Checks 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

stack.size() ⇒ number

Returns 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

stack.clear()

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

stack.toArray() ⇒ 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]

Queue

Represents a queue data structure.

Kind: global class

queue.enqueue(element)

Adds an element to the back of the queue.

Kind: instance method of Queue

ParamTypeDescription
elementTThe element to enqueue.

Example

const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.toArray()); // Output: [1, 2]

queue.dequeue() ⇒ T | undefined

Removes 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]

queue.peek() ⇒ T | undefined

Returns 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]

queue.isEmpty() ⇒ boolean

Checks 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

queue.size() ⇒ number

Returns 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

queue.clear()

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

queue.toArray() ⇒ 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]

TreeNode

Represents a node in a binary search tree.

Kind: global class

BinarySearchTree

Represents a binary search tree.

Kind: global class

binarySearchTree.insert(value)

Inserts a new element into the binary search tree.

Kind: instance method of BinarySearchTree

ParamTypeDescription
valueTThe 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

binarySearchTree.delete(value)

Deletes an element from the binary search tree.

Kind: instance method of BinarySearchTree

ParamTypeDescription
valueTThe 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

binarySearchTree.find(value) ⇒ boolean

Finds an element in the binary search tree.

Kind: instance method of BinarySearchTree
Returns: boolean - true if the element is found, false otherwise.

ParamTypeDescription
valueTThe 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

binarySearchTree.getMin() ⇒ T | null

Gets 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

binarySearchTree.getMax() ⇒ T | null

Gets 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

binarySearchTree.getHeight() ⇒ number

Gets 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

binarySearchTree.traverseInOrder() ⇒ 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]

binarySearchTree.traversePreOrder() ⇒ 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]

binarySearchTree.traversePostOrder() ⇒ 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]

Vertex

Represents a vertex in an undirected graph.

Kind: global class

UndirectedGraph

Represents an undirected graph.

Kind: global class

undirectedGraph.addVertex(value)

Adds a new vertex to the graph.

Kind: instance method of UndirectedGraph

ParamTypeDescription
valueTThe value to associate with the new vertex.

Example

const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');

undirectedGraph.removeVertex(value)

Removes a vertex and all its edges from the graph.

Kind: instance method of UndirectedGraph

ParamTypeDescription
valueTThe 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');

undirectedGraph.addEdge(value1, value2)

Adds an edge between two vertices in the graph.

Kind: instance method of UndirectedGraph

ParamTypeDescription
value1TThe value associated with the first vertex.
value2TThe value associated with the second vertex.

Example

const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');

undirectedGraph.removeEdge(value1, value2)

Removes an edge between two vertices in the graph.

Kind: instance method of UndirectedGraph

ParamTypeDescription
value1TThe value associated with the first vertex.
value2TThe 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');

undirectedGraph.hasVertex(value) ⇒ boolean

Checks 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.

ParamTypeDescription
valueTThe 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

undirectedGraph.hasEdge(value1, value2) ⇒ boolean

Checks if an edge exists between two vertices in the graph.

Kind: instance method of UndirectedGraph
Returns: boolean - true if the edge exists, false otherwise.

ParamTypeDescription
value1TThe value associated with the first vertex.
value2TThe 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

undirectedGraph.getNeighbors(value) ⇒ Array.<T>

Gets an array of neighbors for a given vertex.

Kind: instance method of UndirectedGraph
Returns: Array.<T> - An array of neighbor values.

ParamTypeDescription
valueTThe 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']

KeyValuePair

Represents a key-value pair in a hash table.

Kind: global class

HashTable

Represents a hash table.

Kind: global class

hashTable.put(key, value)

Inserts a key-value pair into the hash table.

Kind: instance method of HashTable

ParamTypeDescription
keyKThe key to insert.
valueVThe value to insert.

Example

const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
hashTable.put('banana', 8);

hashTable.get(key) ⇒ V | undefined

Retrieves 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.

ParamTypeDescription
keyKThe 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

hashTable.remove(key)

Removes a key-value pair associated with a key from the hash table.

Kind: instance method of HashTable

ParamTypeDescription
keyKThe key to remove.

Example

const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
hashTable.remove('apple');
console.log(hashTable.get('apple')); // Output: undefined

hashTable.containsKey(key) ⇒ boolean

Checks if the hash table contains a key.

Kind: instance method of HashTable
Returns: boolean - true if the key exists, false otherwise.

ParamTypeDescription
keyKThe 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

hashTable.keys() ⇒ 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']

hashTable.values() ⇒ 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]

BTreeNode

Represents a node in a B-Tree.

Kind: global class

TrieNode

Represents a node in a Trie.

Kind: global class

Trie

Represents a Trie (prefix tree).

Kind: global class

trie.insert(word)

Inserts a word into the Trie.

Kind: instance method of Trie

ParamTypeDescription
wordstringThe word to insert.

Example

const trie = new Trie();
trie.insert("apple");
trie.insert("app");

trie.search(word) ⇒ boolean

Searches for a word in the Trie.

Kind: instance method of Trie
Returns: boolean - true if the word is found, false otherwise.

ParamTypeDescription
wordstringThe 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

trie.startsWith(prefix) ⇒ boolean

Determines 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.

ParamTypeDescription
prefixstringThe 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

trie.delete(word)

Deletes a word from the Trie.

Kind: instance method of Trie

ParamTypeDescription
wordstringThe word to delete.

Example

const trie = new Trie();
trie.insert("apple");
trie.delete("apple");
console.log(trie.search("apple")); // Output: false

trie.autocomplete(prefix) ⇒ 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.

ParamTypeDescription
prefixstringThe 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: []

SparseMatrix

Represents a sparse matrix.

Kind: global class

new SparseMatrix(rows, cols)

Constructs a sparse matrix with the specified number of rows and columns.

ParamTypeDescription
rowsnumberThe number of rows in the matrix.
colsnumberThe number of columns in the matrix.

Example

const matrix = new SparseMatrix(3, 4);

sparseMatrix.get(row, col) ⇒ number

Gets 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.

ParamTypeDescription
rownumberThe row index (0-based).
colnumberThe 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

sparseMatrix.set(row, col, value)

Sets the value at the specified row and column in the matrix.

Kind: instance method of SparseMatrix

ParamTypeDescription
rownumberThe row index (0-based).
colnumberThe column index (0-based).
valuenumberThe value to set.

Example

const matrix = new SparseMatrix(3, 4);
matrix.set(0, 1, 5);
console.log(matrix.get(0, 1)); // Output: 5

sparseMatrix.transpose() ⇒ SparseMatrix

Transposes 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

sparseMatrix.add(otherMatrix) ⇒ SparseMatrix

Adds two matrices together and returns a new matrix with the result.

Kind: instance method of SparseMatrix
Returns: SparseMatrix - The resulting matrix after addition.

ParamTypeDescription
otherMatrixSparseMatrixThe 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

sparseMatrix.multiply(otherMatrix) ⇒ SparseMatrix

Multiplies two matrices together and returns a new matrix with the result.

Kind: instance method of SparseMatrix
Returns: SparseMatrix - The resulting matrix after multiplication.

ParamTypeDescription
otherMatrixSparseMatrixThe 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

sparseMatrix.compress()

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

BitSet

Represents a BitSet, a data structure for efficient manipulation of bits.

Kind: global class

new BitSet(size)

Constructs a BitSet with the specified number of bits.

ParamTypeDescription
sizenumberThe number of bits in the BitSet.

Example

const bitSet = new BitSet(10);

bitSet.set(index)

Sets the bit at the specified index to 1.

Kind: instance method of BitSet

ParamTypeDescription
indexnumberThe index of the bit to set.

Example

const bitSet = new BitSet(10);
bitSet.set(3);
console.log(bitSet.test(3)); // Output: true

bitSet.clear(index)

Clears the bit at the specified index (sets it to 0).

Kind: instance method of BitSet

ParamTypeDescription
indexnumberThe 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

bitSet.toggle(index)

Toggles the bit at the specified index (flips its value).

Kind: instance method of BitSet

ParamTypeDescription
indexnumberThe 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

bitSet.test(index) ⇒ boolean

Tests 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).

ParamTypeDescription
indexnumberThe index of the bit to test.

Example

const bitSet = new BitSet(10);
bitSet.set(3);
console.log(bitSet.test(3)); // Output: true

bitSet.countSetBits() ⇒ number

Counts 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

bitSet.findNextSetBit(startIndex) ⇒ number

Finds 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.

ParamTypeDescription
startIndexnumberThe 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

CircularBuffer

Represents a Circular Buffer, a data structure for managing a fixed-size buffer with efficient enqueue and dequeue operations.

Kind: global class

new CircularBuffer(size)

Constructs a Circular Buffer with the specified size.

ParamTypeDescription
sizenumberThe maximum size of the buffer.

Example

const circularBuffer = new CircularBuffer<number>(5);

circularBuffer.enqueue(element)

Enqueues an element at the rear of the Circular Buffer.

Kind: instance method of CircularBuffer

ParamTypeDescription
elementTThe element to enqueue.

Example

const circularBuffer = new CircularBuffer<number>(5);
circularBuffer.enqueue(1);
circularBuffer.enqueue(2);

circularBuffer.dequeue() ⇒ T

Dequeues 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

circularBuffer.isFull() ⇒ boolean

Checks 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

circularBuffer.isEmpty() ⇒ boolean

Checks 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

circularBuffer.peek() ⇒ T

Peeks 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

circularBuffer.clear()

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

SplayNode

Represents a node in a self-adjusting list (Splay Tree).

Kind: global class

SelfAdjustingList

Represents a self-adjusting list (Splay Tree).

Kind: global class

selfAdjustingList.splay(element)

Performs a splay operation on the tree to bring the specified element to the root.

Kind: instance method of SelfAdjustingList

ParamTypeDescription
elementTThe element to splay.

Example

const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.splay(1);

selfAdjustingList.insert(element)

Inserts an element into the self-adjusting list.

Kind: instance method of SelfAdjustingList

ParamTypeDescription
elementTThe element to insert.

Example

const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.insert(2);

selfAdjustingList.moveToFront(element)

Moves the specified element to the front of the self-adjusting list.

Kind: instance method of SelfAdjustingList

ParamTypeDescription
elementTThe element to move to the front.

Example

const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.insert(2);
splayTree.moveToFront(1);

selfAdjustingList.insertAfter(target, element)

Inserts an element after a specified element in the self-adjusting list.

Kind: instance method of SelfAdjustingList

ParamTypeDescription
targetTThe element after which to insert.
elementTThe element to insert.

Example

const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.insert(3);
splayTree.insertAfter(1, 2);

__awaiter

This file contains all Wavefuel's async utility functions

Kind: global variable
Author: Mr.Blue

__createBinding

This file contains all Wavefuel's data utility functions

Kind: global variable
Author: Mr.White

__createBinding

This file contains all Wavefuel's file utility functions

Kind: global variable
Author: Mr.Blue

__createBinding

This file contains all Wavefuel's data utility functions

Kind: global variable
Author: Mr.White

__createBinding

This file contains all Wavefuel's data utility functions

Kind: global variable
Author: Mr.White

__createBinding

This file contains all Wavefuel's data utility functions

Kind: global variable
Author: Mr.White

__createBinding

This file contains all Wavefuel's test utility functions

Kind: global variable
Author: Mr.Blue

__createBinding

This file contains all Wavefuel's data utility functions

Kind: global variable
Author: Mr.White MrBlue

cache

In-memory cache for storing cached API responses. You may need to adjust the cache implementation based on your needs.

Kind: global constant

sendGETRequest(url) ⇒ 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.
ParamTypeDescription
urlstringThe URL to send the GET request to.

sendPOSTRequest(url, data) ⇒ 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.
ParamTypeDescription
urlstringThe URL to send the POST request to.
dataRecord.<string, any>The data to send in the request body.

sendPUTRequest(url, data) ⇒ 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.
ParamTypeDescription
urlstringThe URL to send the PUT request to.
dataRecord.<string, any>The data to send in the request body.

sendDELETERequest(url, data) ⇒ 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.
ParamTypeDescription
urlstringThe URL to send the PATCH request to.
dataRecord.<string, any>The data to send in the request body.

sendPATCHRequest(url) ⇒ 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.
ParamTypeDescription
urlstringThe URL to send the DELETE request to.

sendHEADRequest(url) ⇒ 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.
ParamTypeDescription
urlstringThe URL to send the HEAD request to.

sendCustomRequest(url, options) ⇒ 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.
ParamTypeDescription
urlstringThe URL to send the custom request to.
optionsRequestInitThe 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);
  });

serializeData(data) ⇒ string

Serializes an object into a query string format for use in URL parameters.

Kind: global function
Returns: string - The serialized query string.

ParamTypeDescription
dataRecord.<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"

deserializeData(queryString) ⇒ Record.<string, any>

Deserializes a query string into an object.

Kind: global function
Returns: Record.<string, any> - The deserialized object.

ParamTypeDescription
queryStringstringThe 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' }

convertXMLToJSON(xmlString) ⇒ object

Converts an XML string into a JSON object using inbuilt functions.

Kind: global function
Returns: object - The JSON object.

ParamTypeDescription
xmlStringstringThe 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' } }

convertCSVToJSON(csvString, delimiter) ⇒ 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.

ParamTypeDescription
csvStringstringThe CSV string to be converted.
delimiterstringThe 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' }
 ]

formatDataForDisplay(data) ⇒ string

Formats 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.

ParamTypeDescription
dataobjectThe 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"

handleResponse(response) ⇒ 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.
ParamTypeDescription
responseResponseThe 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);
  });

paginateResults(items, pageNumber, pageSize) ⇒ 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.

ParamTypeDescription
itemsArray.<any>The list of items to paginate.
pageNumbernumberThe page number to retrieve (1-based index).
pageSizenumberThe 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]

getNextPageLink(baseUrl, currentPage, pageSize, totalItems) ⇒ string | null

Generates 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.

ParamTypeDescription
baseUrlstringThe base URL of the resource.
currentPagenumberThe current page number (1-based index).
pageSizenumberThe number of items per page.
totalItemsnumberThe 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"

getPreviousPageLink(baseUrl, currentPage, pageSize) ⇒ string | null

Generates 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.

ParamTypeDescription
baseUrlstringThe base URL of the resource.
currentPagenumberThe current page number (1-based index).
pageSizenumberThe 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"

calculateTotalPages(totalItems, pageSize) ⇒ number

Calculates the total number of pages required to paginate a list of items.

Kind: global function
Returns: number - The total number of pages.

ParamTypeDescription
totalItemsnumberThe total number of items to paginate.
pageSizenumberThe 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

handleAPIErrors(response) ⇒ 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.

ParamTypeDescription
responseResponseThe 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
  });

handleRateLimitExceeded(retryAfterSeconds) ⇒ 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.

ParamTypeDescription
retryAfterSecondsnumberThe 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
  });

handleTimeoutError(timeoutMilliseconds) ⇒ 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.

ParamTypeDescription
timeoutMillisecondsnumberThe 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
  });

generateAuthHeaders(username, password) ⇒ Headers

Generates authentication headers for HTTP Basic Authentication.

Kind: global function
Returns: Headers - Authentication headers.

ParamTypeDescription
usernamestringThe username for authentication.
passwordstringThe 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);
  });

authorizeRequest(requestConfig, authToken) ⇒ RequestInit

Authorizes an HTTP request by adding authorization headers.

Kind: global function
Returns: RequestInit - The updated request configuration with authorization headers.

ParamTypeDescription
requestConfigRequestInitThe configuration for the HTTP request.
authTokenstringThe 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);
  });

logAPICall(method, url, headers, [requestBody], [responseBody])

Logs information about an API call.

Kind: global function

ParamTypeDescription
methodstringThe HTTP method of the API call (e.g., 'GET', 'POST').
urlstringThe URL of the API endpoint.
headersHeadersThe request headers.
[requestBody]stringThe request body, if applicable.
[responseBody]stringThe 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);

monitorAPICall(method, url, apiCallPromise) ⇒ 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.

ParamTypeDescription
methodstringThe HTTP method of the API call (e.g., 'GET', 'POST').
urlstringThe URL of the API endpoint.
apiCallPromisePromise.<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);
  });

cacheResponse(cacheKey, response)

Caches an API response using a cache key and stores it in memory.

Kind: global function

ParamTypeDescription
cacheKeystringThe key for caching the API response.
responseResponseThe API response to cache.

getCachedResponse(cacheKey) ⇒ Response | null

Retrieves a cached API response using a cache key.

Kind: global function
Returns: Response | null - The cached API response, or null if not found.

ParamTypeDescription
cacheKeystringThe key for retrieving the cached API response.

validateRequestParameters(params) ⇒ Object

Validates and sanitizes request parameters before making an API request.

Kind: global function
Returns: Object - The sanitized request parameters.

ParamTypeDescription
paramsObjectThe 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);
  });

setRequestContentType(headers, contentType) ⇒ Headers

Sets the "Content-Type" header for an HTTP request.

Kind: global function
Returns: Headers - The updated headers object with the "Content-Type" header.

ParamTypeDescription
headersHeadersThe headers object for the request.
contentTypestringThe 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);
  });

mapAPIDataToModel(apiData) ⇒ Object

Maps API data to a model or object.

Kind: global function
Returns: Object - The mapped model or object.

ParamTypeDescription
apiDataObjectThe 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);

connectWebSocket(url) ⇒ WebSocket

Connects to a WebSocket server.

Kind: global function
Returns: WebSocket - The WebSocket instance representing the connection.

ParamTypeDescription
urlstringThe 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
};

sendWebSocketMessage(socket, message)

Sends a message over a WebSocket connection.

Kind: global function

ParamTypeDescription
socketWebSocketThe WebSocket instance representing the connection.
messagestring | Blob | ArrayBufferThe 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
};

closeWebSocketConnection(socket, [code], [reason])

Closes a WebSocket connection gracefully.

Kind: global function

ParamTypeDefaultDescription
socketWebSocketThe WebSocket instance to close.
[code]number1000A numeric status code indicating the reason for closure.
[reason]stringA 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
};

sanitizeInput(input) ⇒ string

Sanitizes input data to remove potentially harmful characters or validate against specific criteria.

Kind: global function
Returns: string - The sanitized input data.

ParamTypeDescription
inputstringThe 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);

uploadFileToAPI(apiUrl, file) ⇒ Promise.<Response>

Uploads a file to a remote API endpoint.

Kind: global function
Returns: Promise.<Response> - A Promise that resolves with the API response.

ParamTypeDescription
apiUrlstringThe URL of the API endpoint to upload the file to.
fileFileThe 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.');
}

downloadFileFromAPI(apiUrl, fileName)

Initiates the download of a file from a remote API endpoint.

Kind: global function

ParamTypeDescription
apiUrlstringThe URL of the API endpoint to download the file from.
fileNamestringThe 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);

getNearbyLocations(latitude, longitude, radius, category) ⇒ 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.

ParamTypeDescription
latitudenumberThe latitude of the reference location.
longitudenumberThe longitude of the reference location.
radiusnumberThe search radius in meters from the reference location.
categorystringThe category or type of locations to search for (e.g., 'restaurant', 'gas station').

calculateDistance(lat1, lon1, lat2, lon2) ⇒ number

Calculates the distance between two sets of geographical coordinates using the Haversine formula.

Kind: global function
Returns: number - The distance in meters.

ParamTypeDescription
lat1numberLatitude of the first location.
lon1numberLongitude of the first location.
lat2numberLatitude of the second location.
lon2numberLongitude of the second location.

authorizeWithApiKey(apiKey, [headers]) ⇒ Object

Authorizes 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.

ParamTypeDescription
apiKeystringThe API key to be added to the headers.
[headers]ObjectAdditional 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
  });

refreshAccessToken(refreshToken, clientId, clientSecret, tokenEndpoint) ⇒ 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.

ParamTypeDescription
refreshTokenstringThe OAuth refresh token.
clientIdstringThe OAuth client ID.
clientSecretstringThe OAuth client secret.
tokenEndpointstringThe 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);
  });

applyExponentialBackoff(requestFn, maxRetries, baseDelay) ⇒ 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.

ParamTypeDescription
requestFnfunctionA function that performs the network request and returns a Promise.
maxRetriesnumberThe maximum number of retry attempts.
baseDelaynumberThe 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);
  });

checkRateLimitExpiry(rateLimitHeader) ⇒ number

Checks 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.

ParamTypeDescription
rateLimitHeaderstringThe 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));

logError(error, [level])

Logs an error message to the console or a logging service.

Kind: global function

ParamTypeDefaultDescription
errorstring | ErrorThe error message or Error object to be logged.
[level]string"&quot;error&quot;"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);
}

monitorAPICallPerformance(apiEndpoint, apiCall) ⇒ 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.

ParamTypeDescription
apiEndpointstringThe URL or endpoint of the API being called.
apiCallfunctionA 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);
  });

invalidateCache(cacheKey)

Invalidates a cache entry by removing it from the cache.

Kind: global function

ParamTypeDescription
cacheKeystringThe 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);

clearCache()

Clears the entire cache by removing all entries.

Kind: global function
Example

Example usage to clear the entire cache
clearCache();

validateResponseSchema(apiResponse, expectedSchema)

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.
ParamTypeDescription
apiResponseobjectThe API response object to be validated.
expectedSchemaobjectThe 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);
}

parseContentTypeHeader(contentTypeHeader) ⇒ object

Parses 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).

ParamTypeDescription
contentTypeHeaderstringThe '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'

transformDataForExport(data) ⇒ string

Transforms data for export to a CSV file format.

Kind: global function
Returns: string - A CSV-formatted string representing the transformed data.

ParamTypeDescription
dataArray.<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);

subscribeToWebSocketTopic(socket, topic, callback)

Subscribes to a WebSocket topic or channel.

Kind: global function

ParamTypeDescription
socketWebSocketThe WebSocket connection to subscribe with.
topicstringThe name or identifier of the topic or channel to subscribe to.
callbackfunctionA 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);

encryptData(data, encryptionKey, iv) ⇒ string

Encrypts data using the AES-GCM encryption algorithm.

Kind: global function
Returns: string - The encrypted data in hexadecimal format.

ParamTypeDescription
datastringThe data to be encrypted.
encryptionKeystringThe encryption key (must be 32 bytes for AES-256-GCM).
ivstringThe 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);

deleteFileOnAPI(apiUrl, fileId, authToken) ⇒ 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.

ParamTypeDescription
apiUrlstringThe URL of the API endpoint that handles file deletion.
fileIdstringThe identifier or filename of the file to be deleted.
authTokenstringAn 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);
  });

downloadFileAsBase64(fileUrl) ⇒ 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.

ParamTypeDescription
fileUrlstringThe 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);
  });

getDistanceBetweenLocations(lat1, lon1, lat2, lon2) ⇒ number

Calculates 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.

ParamTypeDescription
lat1numberLatitude of the first location in degrees.
lon1numberLongitude of the first location in degrees.
lat2numberLatitude of the second location in degrees.
lon2numberLongitude 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');

get(arr, index) ⇒ any

Retrieves the element at the specified index.

Kind: global function
Returns: any - The element at the specified index.

ParamTypeDescription
arrArray.<any>The array to retrieve the element from.
indexnumberThe 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

set(arr, index, value)

Sets the element at the specified index to a new value.

Kind: global function

ParamTypeDescription
arrArray.<any>The array to modify.
indexnumberThe index of the element to set.
valueanyThe 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]

arrLength(arr) ⇒ number

Returns the number of elements in the array.

Kind: global function
Returns: number - The number of elements in the array.

ParamTypeDescription
arrArray.<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

push(arr, element)

Appends an element to the end of the array.

Kind: global function

ParamTypeDescription
arrArray.<any>The array to push the element into.
elementanyThe 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]

pop(arr) ⇒ any

Removes and returns the last element of the array.

Kind: global function
Returns: any - The last element removed from the array.

ParamTypeDescription
arrArray.<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]

find(arr, target) ⇒ number

Finds 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.

ParamTypeDescription
arrArray.<any>The array to search for the target element.
targetanyThe 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

contains(arr, target) ⇒ boolean

Checks if the array contains a specific element.

Kind: global function
Returns: boolean - true if the array contains the target element, false otherwise.

ParamTypeDescription
arrArray.<any>The array to check for the target element.
targetanyThe 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

copy(arr) ⇒ Array.<any>

Creates a shallow copy of the array.

Kind: global function
Returns: Array.<any> - A shallow copy of the input array.

ParamTypeDescription
arrArray.<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]

clear(arr)

Removes all elements from the array.

Kind: global function

ParamTypeDescription
arrArray.<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: []

reverse(arr)

Reverses the order of elements in the array.

Kind: global function

ParamTypeDescription
arrArray.<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]

promisify(fn) ⇒

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.

ParamDescription
fnThe function to be promisified

promisifyMultiple(functions) ⇒

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.

ParamDescription
functionsType Array - An array of functions to be promisified

promiseTimeout(promise, timeout) ⇒

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.

ParamDescription
promiseType Promise - Th promise to be timed out.
timeoutType Number - Number of seconds for timeout. Default value is 30.

retryPromise(fn, tries, ...args) ⇒

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.

ParamDefaultDescription
fnType Function - The function to be executed
tries3Type number - Number of times the function should retry running. Default value is 3.
...argsType any - parameters of the function.

fetchData(url, [options]) ⇒ 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.
ParamTypeDescription
urlstringThe URL to fetch data from.
[options]ObjectOptional 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);
}

fetchDataPromise(url) ⇒ 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.
ParamTypeDescription
urlstringThe 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);
  });

downloadFile(url, localFilePath) ⇒ 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.
ParamTypeDescription
urlstringThe URL of the file to download.
localFilePathstringThe 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);
}

debounceInput(inputFunction, delay) ⇒ function

Debounce 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.

ParamTypeDescription
inputFunctionfunctionThe function to debounce.
delaynumberThe 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');

memoizeAsyncFunction(asyncFunction) ⇒ function

Memoize 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.

ParamTypeDescription
asyncFunctionfunctionThe 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(count, interval) ⇒ 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.

ParamTypeDescription
countnumberThe number of values to generate.
intervalnumberThe 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)

consumeAsyncGenerator(asyncGenerator, callback) ⇒ 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.

ParamTypeDescription
asyncGeneratorAsyncGenerator.<any, void, undefined>The async generator to consume values from.
callbackfunctionThe 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.

asyncForEach(array, callback) ⇒ 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.

ParamTypeDescription
arrayArray.<any>The array to iterate over.
callbackfunctionThe 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.

asyncMap(array, mapper) ⇒ 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.

ParamTypeDescription
arrayArray.<any>The array of values to map.
mapperfunctionThe 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)

cancelAsyncTask(asyncTask) ⇒ 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.

ParamTypeDescription
asyncTaskPromise.<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.

profileAsyncFunction(asyncFunction) ⇒ 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.

ParamTypeDescription
asyncFunctionfunctionThe 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.

monitorResourceUsageAsync(asyncTask) ⇒ 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.

ParamTypeDescription
asyncTaskfunctionThe 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 }

readJson(path) ⇒ object

Reads 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.
ParamTypeDescription
pathstringThe 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);

writeJson(path, data) ⇒ object

Writes 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.
ParamTypeDescription
pathstringThe path to the JSON file to write.
dataanyThe 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);

json2Csv(data) ⇒ string

Converts an array of JSON objects into a CSV (Comma-Separated Values) string.

Kind: global function
Returns: string - - A CSV string representing the data.

ParamTypeDescription
dataanyAn 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);

removeMissingValues(data) ⇒ 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.

ParamTypeDescription
dataArray.<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]]

scaleNumericFeatures(data) ⇒ 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.

ParamTypeDescription
dataArray.<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]]

oneHotEncode(data, categoricalColumns) ⇒ Array.<Array.<number>>

One-hot encodes categorical variables in a 2D array.

Kind: global function
Returns: Array.<Array.<number>> - - The one-hot encoded data.

ParamTypeDescription
dataArray.<Array.<any>>The input data containing categorical variables.
categoricalColumnsArray.<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]]

zScoreNormalizeData(data) ⇒ 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.

ParamTypeDescription
dataArray.<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]]

splitData(data, splitRatio) ⇒ 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.

ParamTypeDescription
dataArray.<Array.<any>>The input data to be split.
splitRationumberThe 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.

shuffleData(data) ⇒ Array.<Array.<any>>

Shuffles the rows of a 2D array randomly.

Kind: global function
Returns: Array.<Array.<any>> - - The shuffled data.

ParamTypeDescription
dataArray.<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.

resampleData(data, targetColumn, resampleCount) ⇒ Array.<Array.<any>>

Data Resampling (e.g., for imbalanced datasets).

Kind: global function
Returns: Array.<Array.<any>> - - The resampled data with balanced classes.

ParamTypeDescription
dataArray.<Array.<any>>The input data with a target column (binary classification).
targetColumnnumberThe index of the target column (0-based).
resampleCountnumberThe 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).

selectFeatures(data, selectedColumns) ⇒ Array.<Array.<any>>

Feature Selection.

Kind: global function
Returns: Array.<Array.<any>> - - The data with selected features.

ParamTypeDescription
dataArray.<Array.<any>>The input data with features.
selectedColumnsArray.<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).

logTransform(data) ⇒ 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).

ParamTypeDescription
dataArray.<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.

crossValidationSplit(data, folds) ⇒ 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.

ParamTypeDescription
dataArray.<Array.<T>>The input data to be split.
foldsnumberThe 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.

imputeMissingValues(data, imputationValue) ⇒ 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.

ParamTypeDescription
dataArray.<Array.<any>>The input data containing missing values.
imputationValueanyThe 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.

createPolynomialFeatures(data, degree) ⇒ Array.<Array.<number>>

Creates polynomial features for a dataset.

Kind: global function
Returns: Array.<Array.<number>> - - The data with polynomial features.

ParamTypeDescription
dataArray.<Array.<number>>The input data with numeric features.
degreenumberThe 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.

binNumericData(data, numBins) ⇒ Array.<Array.<number>>

Discretizes (bins) numeric data into a specified number of bins.

Kind: global function
Returns: Array.<Array.<number>> - - The binned data.

ParamTypeDescription
dataArray.<Array.<number>>The input data with numeric features.
numBinsnumberThe 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.

encodeOrdinal(data, ordinalColumns, encodingMap) ⇒ 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.

ParamTypeDescription
dataArray.<Array.<any>>The input data containing ordinal categorical columns.
ordinalColumnsArray.<number>An array of column indices containing ordinal categorical columns.
encodingMapObjectA 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.

minMaxScaling(data) ⇒ 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.

ParamTypeDescription
dataArray.<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.

textTokenization(textData) ⇒ 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.

ParamTypeDescription
textDataArray.<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.

removeStopWords(textData) ⇒ 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.

ParamTypeDescription
textDataArray.<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.

stemWords(textData) ⇒ 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.

ParamTypeDescription
textDataArray.<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.

parseDateTime(data, dateTimeColumns) ⇒ 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.

ParamTypeDescription
dataArray.<Array.<any>>The input data containing date and time strings.
dateTimeColumnsArray.<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.

extractTimeFeatures(data) ⇒ 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.

ParamTypeDescription
dataArray.<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.

removeOutliers(data, threshold) ⇒ 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.

ParamTypeDescription
dataArray.<Array.<number>>The input data with numeric features.
thresholdnumberThe 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.

encodeNominal(data, nominalColumns) ⇒ 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.

ParamTypeDescription
dataArray.<Array.<any>>The input data containing nominal categorical columns.
nominalColumnsArray.<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.

standardizeData(data) ⇒ 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.

ParamTypeDescription
dataArray.<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.

augmentImageData(images, augmentationOptions) ⇒ 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.
ParamTypeDescription
imagesArray.<MyImageData>An array of image data to be augmented.
augmentationOptionsAugmentationOptionsOptions 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.

loadCSV(filename) ⇒ 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.
ParamTypeDescription
filenamestringThe 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);
  });

filterData(data, filterFn) ⇒ 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.

ParamTypeDescription
dataArray.<Data>The array of Data objects to filter.
filterFnfunctionThe 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 }]

mapData(data, mapFn) ⇒ 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.

ParamTypeDescription
dataArray.<Data>The array of Data objects to map.
mapFnfunctionThe 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 },
]

sortData(data, key, [ascending]) ⇒ 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.

ParamTypeDefaultDescription
dataArray.<Data>The array of Data objects to sort.
keystringThe key by which to sort the objects.
[ascending]booleantrueWhether 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 }]

groupBy(data, key) ⇒ 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.

ParamTypeDescription
dataArray.<Data>The array of Data objects to group.
keystringThe 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 }]

aggregate(data, groupKey, aggregationFn) ⇒ 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.

ParamTypeDescription
dataArray.<Data>The array of Data objects to aggregate.
groupKeystringThe key by which to group the data.
aggregationFnfunctionThe 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

exportCSV(data, filename)

Exports an array of data to a CSV file.

Kind: global function

ParamTypeDescription
dataArray.<Data>An array of data to export.
filenamestringThe 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');

minMaxNormalizeData(data) ⇒ Array.<number>

Normalizes an array of numeric data using min-max scaling.

Kind: global function
Returns: Array.<number> - The normalized data.

ParamTypeDescription
dataArray.<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]

countWords(text) ⇒ number

Counts the number of words in a text string.

Kind: global function
Returns: number - The number of words in the text.

ParamTypeDescription
textstringThe input text.

Example

Example usage:
const text = "This is an example sentence.";
const wordCount = countWords(text);
console.log(wordCount);
Output: 5

findKeywords(text, keywords) ⇒ 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.

ParamTypeDescription
textstringThe input text.
keywordsArray.<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"]

format_date(date, pattern) ⇒ string

Format 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.

ParamTypeDescription
dateDateThe date object to format.
patternstringThe 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

to_human_readable(sizeInBytes) ⇒ string

Convert 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:

  • 1 KB (kilobyte) = 1024 bytes
  • 1 MB (megabyte) = 1024 KB
  • 1 GB (gigabyte) = 1024 MB
  • 1 TB (terabyte) = 1024 GB
  • 1 PB (petabyte) = 1024 TB
  • 1 EB (exabyte) = 1024 PB
  • 1 ZB (zettabyte) = 1024 EB
  • 1 YB (yottabyte) = 1024 ZB
ParamTypeDescription
sizeInBytesnumberThe 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

parse_date(dateString, format) ⇒ Date | null

Parse 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:

  • 'YYYY' for year
  • 'MM' for month
  • 'DD' for day
  • 'hh' for hours
  • 'mm' for minutes
  • 'ss' for seconds

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.

  • Months are zero-based, meaning January is represented as 0, February as 1, and so on.
  • Be aware that this function does not perform strict date validation and may accept invalid dates if the provided format matches.
ParamTypeDescription
dateStringstringThe date string to parse.
formatstringThe 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)

parse_iso8601(iso8601String) ⇒ Date | null

Parse 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.

  • ISO 8601 supports various formats, including date-only, date-time with timezone, and more.
  • Be aware that this function does not perform strict date validation and may accept invalid ISO 8601 date strings if they match the general format.
ParamTypeDescription
iso8601StringstringThe 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)

compare_dates(date1, date2) ⇒ number

Compare two JavaScript Date objects to determine their chronological order.

This function compares two Date objects and returns an integer value indicating their chronological order:

  • If date1 is earlier than date2, it returns a negative value.
  • If date1 is later than date2, it returns a positive value.
  • If both dates are equal, it returns 0.

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.

  • Date and time are considered when making the comparison.
  • Be cautious when comparing dates with different time zones; time zone differences may affect the comparison results.
ParamTypeDescription
date1DateThe first Date object to compare.
date2DateThe 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.

is_past(date) ⇒ boolean

Check 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.

  • It returns true if the provided date is earlier than the current date and time; otherwise, it returns false.
  • Time zone differences should be taken into account when comparing dates across different time zones.
ParamTypeDescription
dateDateThe 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.

is_future(date) ⇒ boolean

Check 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.

  • It returns true if the provided date is later than the current date and time; otherwise, it returns false.
  • Time zone differences should be taken into account when comparing dates across different time zones.
ParamTypeDescription
dateDateThe 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.

add_days(date, daysToAdd) ⇒ Date

Add 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.

  • The original Date object remains unchanged; a new Date object is returned with the updated date.
ParamTypeDescription
dateDateThe Date object to which days will be added.
daysToAddnumberThe 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)

subtract_days(date, daysToSubtract) ⇒ Date

Subtract 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.

  • The original Date object remains unchanged; a new Date object is returned with the updated date.
ParamTypeDescription
dateDateThe Date object from which days will be subtracted.
daysToSubtractnumberThe 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)

days_between_dates(startDate, endDate) ⇒ number

Calculate 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.

  • A positive value indicates that endDate is later than startDate.
  • A negative value indicates that endDate is earlier than startDate.
  • A value of 0 indicates that both dates are the same.
  • Time zone differences should be taken into account when comparing dates across different time zones.
ParamTypeDescription
startDateDateThe starting Date object.
endDateDateThe 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

is_valid_date(date) ⇒ boolean

Check 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.

  • It returns true if the date is valid, and false if it is not.
ParamTypeDescription
dateDateThe 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

is_leap_year(year) ⇒ boolean

Check 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.

  • A leap year is a year that is evenly divisible by 4, except for years that are divisible by 100 but not divisible by 400.
  • It returns true if the year is a leap year, and false otherwise.
ParamTypeDescription
yearnumberThe 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

generate_date_range(startDate, endDate, [step]) ⇒ 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.

  • The optional step parameter allows you to specify the interval between dates in days.
  • The generated array includes both startDate and endDate if they are within the specified range.
ParamTypeDefaultDescription
startDateDateThe start date of the range (inclusive).
endDateDateThe end date of the range (inclusive).
[step]number1Optional 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

generate_month_range(startDate, endDate) ⇒ 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.

  • Both startDate and endDate are included in the generated array if they fall within the specified range.
ParamTypeDescription
startDateDateThe start date of the range (inclusive).
endDateDateThe 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

date_to_unix_timestamp(date) ⇒ number

Convert 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).

  • The function converts the provided Date object to a Unix timestamp.
ParamTypeDescription
dateDateThe 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

unix_timestamp_to_date(timestamp) ⇒ Date

Convert 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).

  • The function converts the provided Unix timestamp to a JavaScript Date object.
ParamTypeDescription
timestampnumberThe 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)

get_day_of_week(date) ⇒ string

Get 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.

  • The day of the week is returned as a string (e.g., "Sunday", "Monday").
ParamTypeDescription
dateDateThe 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

is_weekend(date) ⇒ boolean

Check 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.

  • It returns true if the date is a weekend day and false if it is a weekday.
ParamTypeDescription
dateDateThe 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

add_business_days(date, daysToAdd) ⇒ Date

Add 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).

  • The function calculates the new date after adding the specified business days while skipping weekends.
ParamTypeDescription
dateDateThe Date object to which business days will be added.
daysToAddnumberThe 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

next_business_day(date) ⇒ Date

Get 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).

  • The function finds the next business day after the provided date, skipping weekends.
ParamTypeDescription
dateDateThe 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

convert_timezone(date, targetTimeZone) ⇒ Date

Convert 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.

  • The targetTimeZone parameter should be provided in the IANA Time Zone format (e.g., "America/New_York").
ParamTypeDescription
dateDateThe Date object to convert.
targetTimeZonestringThe 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)

calculate_age(birthdate, referenceDate) ⇒ number

Calculate 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.

  • The birthdate should be a Date object representing the person's date of birth.
  • The reference date is usually the current date, but it can be any Date object for custom calculations.
  • The function returns the age as a number (integer).
ParamTypeDescription
birthdateDateThe Date object representing the birthdate.
referenceDateDateThe 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)

randomDate(startDate, endDate) ⇒ Date

Generates a random date within a specified date range.

Kind: global function
Returns: Date - A random date within the specified range.

ParamTypeDescription
startDateDateThe start date of the date range.
endDateDateThe 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.

weightedRandomDate(startDate, endDate, weightedDays) ⇒ Date

Generates 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.

ParamTypeDescription
startDateDateThe start date of the date range.
endDateDateThe end date of the date range.
weightedDaysRecord.<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.

shiftDate(date, daysToShift) ⇒ Date

Shifts a given date by a specified number of days and returns the shifted date.

Kind: global function
Returns: Date - The shifted date.

ParamTypeDescription
dateDateThe input date to shift.
daysToShiftnumberThe 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"

formatDateDifference(startDate, endDate) ⇒ string

Formats 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.

ParamTypeDescription
startDateDateThe start date.
endDateDateThe 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"

adjustForTimezoneOffset(date, timezoneOffset) ⇒ Date

Adjusts 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.

ParamTypeDescription
dateDateThe input date to adjust.
timezoneOffsetnumberThe 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

get_week_number(date, [weekNumberingSystem]) ⇒ number

Get 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.

  • The week numbering system can be specified as "iso" (ISO 8601) or "us" (US standard).
  • In the ISO system, weeks start on Monday and the first week of the year contains the first Thursday.
  • In the US system, weeks start on Sunday, and the first week of the year contains January 1st.
  • The function returns the week number as a number.
ParamTypeDefaultDescription
dateDateThe 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

deserialize_date(serializedDate, format) ⇒ Date | null

Deserialize 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.

  • Common format placeholders include "YYYY" for year, "MM" for month, and "DD" for day.
  • You can define your own format patterns using these placeholders (e.g., "YYYY-MM-DD HH:mm:ss").
  • If deserialization fails due to an invalid format, the function returns null.
ParamTypeDescription
serializedDatestringThe serialized string representation of the date.
formatstringThe 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

serialize_date(date, format) ⇒ string

Serialize 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.

  • Common format placeholders include "YYYY" for year, "MM" for month, and "DD" for day.
  • You can define your own format patterns using these placeholders (e.g., "YYYY-MM-DD HH:mm:ss").
  • The function returns the serialized Date as a string based on the specified format pattern.
ParamTypeDescription
dateDateThe Date object to serialize.
formatstringThe 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

is_date_in_range(date, startDate, endDate) ⇒ boolean

Check 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.

  • The start and end dates are considered inclusive, meaning that if the provided date matches either the start or end date, it is considered within the range.
  • The function returns true if the date is within the specified range and false otherwise.
ParamTypeDescription
dateDateThe Date object to check.
startDateDateThe start date of the date range (inclusive).
endDateDateThe 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

get_fiscal_period(date, fiscalYearStartMonth) ⇒ number

Get 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.

  • Fiscal periods are typically used for financial reporting and can vary depending on the organization's fiscal year.
  • The function returns the fiscal period as a number within the range of 1 to 12.
ParamTypeDescription
dateDateThe Date object for which to get the fiscal period.
fiscalYearStartMonthnumberThe 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

get_quarter(date) ⇒ number

Get 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.

  • Quarters are numbered from 1 to 4, with 1 being January to March, 2 being April to June, and so on.
  • The function returns the quarter as a number.
ParamTypeDescription
dateDateThe 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

read_file_contents(filename) ⇒ string

Reads 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.

ParamTypeDescription
filenamestringThe path to the file to read.

Example

const fileContent = read_file_contents('example.txt');
console.log(fileContent);

write_to_file(filename, data, append)

Writes data to a file, either by overwriting the existing content or appending to it.

Kind: global function

ParamTypeDefaultDescription
filenamestringThe path to the file to write to.
datastringThe data to write to the file.
appendbooleanfalseWhether 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);

copy_file(source, destination)

Copies the contents of one file to another.

Kind: global function

ParamTypeDescription
sourcestringThe path to the source file to copy from.
destinationstringThe path to the destination file to copy to.

Example

copy_file('source.txt', 'destination.txt');

move_file(source, destination)

Renames a file or moves it to a different directory.

Kind: global function

ParamTypeDescription
sourcestringThe current path of the file.
destinationstringThe new path or directory of the file.

Example

move_file('oldname.txt', 'newname.txt');
move_file('file.txt', 'directory/newfile.txt');

file_exists(filename) ⇒ boolean

Checks if a file exists at a specified path.

Kind: global function
Returns: boolean - true if the file exists, false otherwise.

ParamTypeDescription
filenamestringThe path to the file to check.

Example

if (file_exists('example.txt')) {
  console.log('File exists!');
}

delete_file(filename)

Deletes a file from the file system.

Kind: global function

ParamTypeDescription
filenamestringThe path to the file to delete.

Example

delete_file('oldfile.txt');

get_file_size(filename) ⇒ number

Determines the size of a file in bytes.

Kind: global function
Returns: number - The size of the file in bytes.

ParamTypeDescription
filenamestringThe path to the file.

Example

const fileSize = get_file_size('document.pdf');
console.log(`File size: ${fileSize} bytes`);

get_file_type(filename) ⇒ string

Determines the type or format of a file (e.g., text, binary, JSON, XML).

Kind: global function
Returns: string - The file type or format.

ParamTypeDescription
filenamestringThe path to the file.

Example

const fileType = get_file_type('data.json');
console.log(`File type: ${fileType}`);

set_file_permissions(filename, permissions)

Sets or modifies file permissions (e.g., read, write, execute) on a file.

Kind: global function

ParamTypeDescription
filenamestringThe path to the file.
permissionsnumberThe permissions to set.

Example

set_file_permissions('file.txt', 0o755); // Give read, write, and execute permissions to owner, and read and execute to others.

read_csv_file(filename) ⇒ 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.

ParamTypeDescription
filenamestringThe path to the CSV file to read.

Example

const csvData = await read_csv_file('data.csv');
console.log(csvData);

read_json_file(filename) ⇒ any

Reads data from a JSON file and parses it into a dictionary or an object.

Kind: global function
Returns: any - The parsed JSON data.

ParamTypeDescription
filenamestringThe path to the JSON file to read.

Example

const jsonData = read_json_file('data.json');
console.log(jsonData);

write_json_file(filename, data)

Writes data from a dictionary or an object to a JSON file.

Kind: global function

ParamTypeDescription
filenamestringThe path to the JSON file to write.
dataanyThe data to write to the JSON file.

Example

const data = { name: 'Alice', age: 30 };
write_json_file('output.json', data);

compress_file(filename, archive_filename)

Compresses a file into an archive (e.g., ZIP).

Kind: global function

ParamTypeDescription
filenamestringThe path to the file to compress.
archive_filenamestringThe path and filename for the compressed archive.

Example

compress_file('file.txt', 'file.zip');

decompress_file(archive_filename, destination)

Decompresses an archived file.

Kind: global function

ParamTypeDescription
archive_filenamestringThe path to the compressed archive file.
destinationstringThe path to the destination directory.

Example

decompress_file('file.zip', 'extracted/');

read_text_file(filename, encoding) ⇒ string

Reads 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.

ParamTypeDescription
filenamestringThe path to the text file to read.
encodingcrypto.EncodingThe character encoding to use (e.g., 'utf-8').

Example

const fileContent = read_text_file('textfile.txt', 'utf-8');
console.log(fileContent);

calculate_file_hash(filename, hash_algorithm) ⇒ string

Calculates hash values (e.g., MD5, SHA-256) for a file's content.

Kind: global function
Returns: string - The calculated hash value.

ParamTypeDescription
filenamestringThe path to the file for which to calculate the hash.
hash_algorithmstringThe hash algorithm to use (e.g., 'md5', 'sha256').

Example

const md5Hash = calculate_file_hash('file.txt', 'md5');
console.log(`MD5 Hash: ${md5Hash}`);

compare_files(file1, file2) ⇒ boolean

Compares two files to check if their contents are identical.

Kind: global function
Returns: boolean - true if the files have identical contents, false otherwise.

ParamTypeDescription
file1stringThe path to the first file for comparison.
file2stringThe 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.');
}

search_in_file(filename, search_pattern) ⇒ boolean

Searches for a specific string or pattern within a file.

Kind: global function
Returns: boolean - true if the pattern is found, false otherwise.

ParamTypeDescription
filenamestringThe path to the file to search in.
search_patternstring | RegExpThe 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.');
}

backup_file(filename, backup_directory)

Creates backup copies of files in a specified directory.

Kind: global function

ParamTypeDescription
filenamestringThe path to the file to create a backup of.
backup_directorystringThe directory where backup copies will be stored.

Example

backup_file('important.txt', 'backup/');

change_file_timestamp(filename, timestamp_type, new_timestamp)

Changes the creation, modification, or access timestamps of a file.

Kind: global function

ParamTypeDescription
filenamestringThe path to the file to modify timestamps for.
timestamp_typestringThe type of timestamp to change ('atime', 'mtime', or 'ctime').
new_timestampDateThe new timestamp to set.

Example

const newDate = new Date('2023-01-01T00:00:00Z');
change_file_timestamp('file.txt', 'mtime', newDate);

merge_files(output_filename, input_files)

Merges the contents of multiple files into a single file.

Kind: global function

ParamTypeDescription
output_filenamestringThe path to the output file where merged content will be saved.
input_filesArray.<string>An array of paths to the input files to be merged.

Example

merge_files('merged.txt', ['file1.txt', 'file2.txt', 'file3.txt']);

read_file_in_chunks(filename, chunk_size) ⇒ Array.<Buffer>

Reads a file in smaller chunks to conserve memory.

Kind: global function
Returns: Array.<Buffer> - An array of chunks.

ParamTypeDescription
filenamestringThe path to the file to read.
chunk_sizenumberThe size of each chunk in bytes.

Example

const chunks = read_file_in_chunks('largefile.txt', 1024); // Read in 1 KB chunks

check_file_permissions(filename, permission_type) ⇒ boolean

Checks 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.

ParamTypeDescription
filenamestringThe path to the file to check permissions for.
permission_typestringThe 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.');
}

archive_files(output_archive, input_files)

Archives files into a single compressed file format (e.g., zip, tar).

Kind: global function

ParamTypeDescription
output_archivestringThe path and filename for the output archive.
input_filesArray.<string>An array of paths to the input files to be archived.

Example

archive_files('my_archive.zip', ['file1.txt', 'file2.txt']);

count_lines_in_file(filename) ⇒ number

Counts the number of lines in a text file.

Kind: global function
Returns: number - The number of lines in the file.

ParamTypeDescription
filenamestringThe path to the text file to count lines in.

Example

const lineCount = count_lines_in_file('textfile.txt');
console.log(`Line count: ${lineCount}`);

change_file_owner(filename, new_owner)

Changes the owner of a file.

Kind: global function

ParamTypeDescription
filenamestringThe path to the file to change ownership for.
new_ownerstringThe username or UID of the new owner.

Example

change_file_owner('file.txt', 'newuser');

copy_permissions(source_file, destination_file)

Copies permissions from one file to another.

Kind: global function

ParamTypeDescription
source_filestringThe path to the source file to copy permissions from.
destination_filestringThe path to the destination file to apply permissions to.

Example

copy_permissions('source.txt', 'destination.txt');

get_file_metadata(filename) ⇒ fs.Stats

Retrieves metadata about a file, such as creation date, modification date, and size.

Kind: global function
Returns: fs.Stats - An object containing file metadata.

ParamTypeDescription
filenamestringThe path to the file to retrieve metadata for.

Example

const metadata = get_file_metadata('file.txt');
console.log(metadata);

encrypt_file(filename, encryption_key)

Encrypts a file using a specified encryption key.

Kind: global function

ParamTypeDescription
filenamestringThe path to the file to encrypt.
encryption_keystringThe encryption key.

Example

encrypt_file('file.txt', 'mysecretkey');

decrypt_file(encrypted_filename, decryption_key)

Decrypts an encrypted file.

Kind: global function

ParamTypeDescription
encrypted_filenamestringThe path to the encrypted file.
decryption_keystringThe decryption key.

Example

decrypt_file('encrypted.txt', 'mysecretkey');

modify_line_in_file(filename, line_number, new_content)

Modifies a specific line in a text file.

Kind: global function

ParamTypeDescription
filenamestringThe path to the text file.
line_numbernumberThe line number to modify (1-based index).
new_contentstringThe new content to replace the line with.

Example

modify_line_in_file('textfile.txt', 3, 'Updated line content');

remove_file_permissions(filename, permissions)

Removes specific permissions from a file.

Kind: global function

ParamTypeDescription
filenamestringThe path to the file to remove permissions from.
permissionsstringThe permissions to remove (e.g., 'read', 'write', 'execute').

Example

remove_file_permissions('file.txt', 'write');

upload_file(local_filename, remote_destination)

Uploads a file to a remote server.

Kind: global function

ParamTypeDescription
local_filenamestringThe path to the local file to upload.
remote_destinationstringThe destination on the remote server where the file will be uploaded.

Example

upload_file('localfile.txt', 'remote_server:/path/to/destination/');

download_file(remote_filename, local_destination)

Downloads a file from a remote server.

Kind: global function

ParamTypeDescription
remote_filenamestringThe path to the file on the remote server to download.
local_destinationstringThe local destination where the file will be saved.

Example

download_file('remote_server:/path/to/remotefile.txt', 'localfile.txt');

convert_file_encoding(input_filename, output_filename, source_encoding, target_encoding)

Converts the encoding of a text file.

Kind: global function

ParamTypeDescription
input_filenamestringThe path to the input file with the source encoding.
output_filenamestringThe path to the output file with the target encoding.
source_encodingstringThe source encoding of the file (e.g., 'utf-8', 'utf-16').
target_encodingstringThe 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');

filter_file_lines(input_filename, output_filename, filter_function)

Filters lines in a text file based on a custom filter function.

Kind: global function

ParamTypeDescription
input_filenamestringThe path to the input text file.
output_filenamestringThe path to the output text file with filtered lines.
filter_functionfunctionThe 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);

check_file_ownership(filename, user)

Checks if a file is owned by a specific user.

Kind: global function

ParamTypeDescription
filenamestringThe path to the file to check ownership.
userstringThe user to check ownership against.

Example

check_file_ownership('file.txt', 'john');

rotate_file_backups(backup_directory, max_backups)

Rotates and manages a limited number of backup copies of a file.

Kind: global function

ParamTypeDescription
backup_directorystringThe directory where backup copies will be stored.
max_backupsnumberThe maximum number of backup copies to retain.

Example

rotate_file_backups('/backup', 5);

getFunctionNamesInFile(filePath) ⇒ 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.
ParamTypeDescription
filePathstringThe 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);

latLonDistanceInKm(lat1, lon1, lat2, lon2) ⇒

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.

ParamDescription
lat1(type: number) latitude1
lon1(type: number) longitude1
lat2(type: number) latitude2
lon2(type: number) longitude2

getUserLocation() ⇒ 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}`);
}

latLonDistanceInMeters(lat1, lon1, lat2, lon2) ⇒ number

This 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.

ParamTypeDescription
lat1numberLatitude of the first point in degrees.
lon1numberLongitude of the first point in degrees.
lat2numberLatitude of the second point in degrees.
lon2numberLongitude 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`);

calculateBearing(lat1, lon1, lat2, lon2) ⇒ number

This 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°).

ParamTypeDescription
lat1numberLatitude of the first point in degrees.
lon1numberLongitude of the first point in degrees.
lat2numberLatitude of the second point in degrees.
lon2numberLongitude 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`);

areCoordinatesValid(lat, lon) ⇒ boolean

This 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.

ParamTypeDescription
latnumberLatitude to check (-90 to 90 degrees).
lonnumberLongitude to check (-180 to 180 degrees).

Example

const isValid = areCoordinatesValid(40.7128, -74.0060);
console.log(`Coordinates are valid: ${isValid}`);

formatDistance(distanceInMeters, units) ⇒ string

This 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.

ParamTypeDescription
distanceInMetersnumberDistance 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}`);

metersToPixels(distanceInMeters, scaleInMetersPerPixel) ⇒ number

This 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.

ParamTypeDescription
distanceInMetersnumberDistance in meters to convert to pixels.
scaleInMetersPerPixelnumberMap'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}`);

formatLogArguments(args) ⇒

Kind: global function
Returns: args

Param
args

getStackInfo()

Parses and returns info about the call stack at the given index. Copied Code from Src: https://gist.github.com/ManotLuijiu/8f0be2f0ac0a8f6dd5dc47e2db332600

Kind: global function

initLogger(fileUrl) ⇒

Initiate a Logger

Kind: global function
Returns: logger object

ParamDescription
fileUrlURL of File for storage.

initiateLogger(fileUrl) ⇒

Initiate a Logger

Kind: global function
Returns: logger object

ParamTypeDescription
fileUrlstringURL of File for storage.

absolute(num) ⇒ number

Calculates 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.

ParamTypeDescription
numnumberThe 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)

squareRoot(num) ⇒ number

Calculates 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.

ParamTypeDescription
numnumberThe 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

cubeRoot(num) ⇒ number

Calculates 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.

ParamTypeDescription
numnumberThe 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

multiplyArray(array) ⇒ number

Multiplies 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.

ParamTypeDescription
arrayArray.<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)

geometricMean(array) ⇒ number

Calculates 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.

ParamTypeDescription
arrayArray.<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)

median(array) ⇒ number

Calculates 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.

ParamTypeDescription
arrayArray.<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)

mode(array) ⇒ number

Finds 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.

ParamTypeDescription
arrayArray.<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)

meanSquareError(array) ⇒ number

Calculates 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.

ParamTypeDescription
arrayArray.<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)

variance(array) ⇒ number

Calculates 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.

ParamTypeDescription
arrayArray.<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)

standardDeviation(array) ⇒ number

Calculates 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.

ParamTypeDescription
arrayArray.<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)

percentileRank(array, percentile) ⇒ 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.

ParamTypeDescription
arrayArray.<number>An array of numbers for which to calculate the percentile rank.
percentilenumberThe 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)

percentile(array, key) ⇒ number

Calculates 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.

ParamTypeDescription
arrayArray.<number>An array of numbers for which to calculate the percentile rank.
keynumberThe 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)

addPercentage(num, percentage) ⇒ number

Adds 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.

ParamTypeDescription
numnumberThe number to which to add the percentage.
percentagenumberThe 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

sin(radians) ⇒ number

Calculates 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.

ParamTypeDescription
radiansnumberThe 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)

cos(radians) ⇒ number

Calculates 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.

ParamTypeDescription
radiansnumberThe 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)

tan(radians) ⇒ number

Calculates 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.

ParamTypeDescription
radiansnumberThe 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)

cosec(radians) ⇒ number

Calculates 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.

ParamTypeDescription
radiansnumberThe 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)

sec(radians) ⇒ number

Calculates 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.

ParamTypeDescription
radiansnumberThe 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)

cot(radians) ⇒ number

Calculates 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.

ParamTypeDescription
radiansnumberThe 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)

asin(num) ⇒ number

Calculates 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.

ParamTypeDescription
numnumberThe 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)

acos(num) ⇒ number

Calculates 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.

ParamTypeDescription
numnumberThe 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)

atan(num) ⇒ number

Calculates 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.

ParamTypeDescription
numnumberThe 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)

acosec(num) ⇒ number

Calculates 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.

ParamTypeDescription
numnumberThe 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)

asec(num) ⇒ number

Calculates 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.

ParamTypeDescription
numnumberThe 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)

acot(num) ⇒ number

Calculates 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.

ParamTypeDescription
numnumberThe 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)

atan2(x, y) ⇒ number

Calculates 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.

ParamTypeDescription
xnumberThe y-coordinate.
ynumberThe 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)

distance(x1, y1, x2, y2) ⇒ number

Calculates 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.

ParamTypeDescription
x1numberThe x-coordinate of the first point.
y1numberThe y-coordinate of the first point.
x2numberThe x-coordinate of the second point.
y2numberThe 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)

deg2Rad(degree) ⇒ number

Converts 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).

ParamTypeDescription
degreenumberThe 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)

rad2Deg(radians) ⇒ number

Converts 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).

ParamTypeDescription
radiansnumberThe 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)

celsius2fahren(celsius) ⇒ number

Converts 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.

ParamTypeDescription
celsiusnumberThe 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)

fahren2celsius(fahrenheit) ⇒ number

Converts 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.

ParamTypeDescription
fahrenheitnumberThe 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)

celsius2kelvin(celsius) ⇒ number

Converts 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.

ParamTypeDescription
celsiusnumberThe 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)

kelvin2celsius(kelvin) ⇒ number

Converts 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.

ParamTypeDescription
kelvinnumberThe 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)

fahren2kelvin(fahrenheit) ⇒ number

Converts 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.

ParamTypeDescription
fahrenheitnumberThe 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)

kelvin2fahren(kelvin) ⇒ number

Converts 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.

ParamTypeDescription
kelvinnumberThe 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)

serializeJson(object) ⇒ string

Serialize an object to a JSON-formatted string.

Kind: global function
Returns: string - The JSON-formatted string representation of the object.

ParamTypeDescription
objectTThe object to serialize.

Example

const data = { name: 'John', age: 30 };
const jsonString = serializeJson(data);
Returns '{"name":"John","age":30}'

deSerializeJson(serializedData) ⇒ T | null

Deserialize 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.

ParamTypeDescription
serializedDatastringThe JSON-formatted string to deserialize.

Example

const jsonString = '{"name":"John","age":30}';
const data = deSerializeJson<Data>(jsonString);
Returns { name: 'John', age: 30 }

serialize(data, [options]) ⇒ string | null

Serializes data into a string representation.

Kind: global function
Returns: string | null - The serialized data as a string, or null if serialization fails.

ParamTypeDescription
dataTThe data to be serialized.
[options]SerializationOptionsSerialization options (optional).

Example

const dataToSerialize = { name: "John", age: 30 };
const serializedData = serialize(dataToSerialize, { prettyPrint: true });
if (serializedData !== null) {
  console.log(serializedData);
}

serializeCSV(data, [options]) ⇒ string

Serialize 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).
ParamTypeDescription
dataArray.<T>The data to be serialized.
[options]CSVSerializationOptionsSerialization options (optional).

Example

const data = [...]; // Data to be serialized to CSV
const csv = serializeCSV(data);
console.log(csv);

deserialize(serializedData, customDeserializer) ⇒ T | null

Deserializes 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.

ParamTypeDescription
serializedDatastringThe serialized data as a string.
customDeserializerfunctionA 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

deserializeCSV(csvString) ⇒ Array.<T> | null

Deserializes 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.
ParamTypeDescription
csvStringstringThe 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.

deepClone(data) ⇒ T

Deep clones an object, including nested objects and arrays.

Kind: global function
Returns: T - The deep-cloned data.

ParamTypeDescription
dataTThe 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);

deepEqual(obj1, obj2, [options]) ⇒ boolean

Deeply 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.

ParamTypeDescription
obj1TThe first object to compare.
obj2TThe second object to compare.
[options]DeepEqualityOptionsDeep 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

validateSchema(data, schema) ⇒ ValidationResult

Validates 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.

ParamTypeDescription
dataTThe data object to be validated.
schemaobjectThe 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);
}

compress(data, [options]) ⇒ Uint8Array

Compresses 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.

ParamTypeDescription
dataUint8Array | stringThe data to be compressed, either as a Uint8Array or a string.
[options]CompressionOptionsCompression options (optional).

Example

const dataToCompress = "This is some data to compress.";
const compressedData = compress(dataToCompress);
console.log(compressedData);

decompress(compressedData, [options]) ⇒ Uint8Array | string

Decompresses 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.
ParamTypeDescription
compressedDataUint8ArrayThe compressed data to decompress.
[options]CompressionOptionsOptional 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"

convertToJSON(data, [options]) ⇒ string | null

Converts 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).

ParamTypeDescription
dataanyThe data to be converted to JSON.
[options]JSONOptionsJSON formatting options (optional).

Example

const dataToConvert = { name: "John", age: 30 };
const jsonData = convertToJSON(dataToConvert, { prettyPrint: true });
console.log(jsonData);

convertFromJSON(jsonData, [options]) ⇒ any | null

Converts 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.

ParamTypeDescription
jsonDatastringThe JSON data to be converted to JavaScript.
[options]JSONOptionsJSON parsing options (optional).

Example

const jsonData = '{"name": "John", "age": 30}';
const jsData = convertFromJSON(jsonData);
console.log(jsData);

handleSerializationError(error, [options]) ⇒ void

Handles serialization errors with optional error-handling options.

Kind: global function
Throws:

  • Error Throws an error if the error-handling options are invalid.
ParamTypeDescription
errorErrorThe error object representing the serialization error.
[options]SerializationErrorOptionsError-handling options (optional).

Example

try {
  // Code that may throw a serialization error
} catch (error) {
  handleSerializationError(error, { logError: true, errorMessage: 'Failed to serialize data.' });
}

handleDeserializationError(error, [options]) ⇒ void

Handles deserialization errors with optional error-handling options.

Kind: global function
Throws:

  • Error Throws an error if the error-handling options are invalid.
ParamTypeDescription
errorErrorThe error object representing the deserialization error.
[options]DeserializationErrorOptionsError-handling options (optional).

Example

try {
  // Code that may throw a deserialization error
} catch (error) {
  handleDeserializationError(error, { logError: true, errorMessage: 'Failed to deserialize data.' });
}

validateSerializedData(serializedData, format, [options]) ⇒ boolean

Validates 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.

ParamTypeDescription
serializedDatastringThe serialized data to be validated.
formatstringThe format of the serialized data (e.g., "json", "xml", "csv").
[options]ValidationOptionsValidation 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.");
}

stringifyJSON(jsonObj, prettyPrint) ⇒ string

Stringify a JSON object with optional pretty-printing.

Kind: global function
Returns: string - The stringified JSON.

ParamTypeDefaultDescription
jsonObjanyThe JSON object to stringify.
prettyPrintbooleanfalseWhether 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
}

parseJSON(jsonString) ⇒ any | null

Parse 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.

ParamTypeDescription
jsonStringstringThe JSON string to parse.

Example

const jsonString = '{"name":"John","age":30}';
const parsedJSON = parseJSON(jsonString);
if (parsedJSON !== null) {
    console.log(parsedJSON.name); // Output: John
}

deepCloneJSON(jsonObj) ⇒ any

Deep clone a JSON object to prevent reference sharing.

Kind: global function
Returns: any - The deep-cloned JSON object.

ParamTypeDescription
jsonObjanyThe JSON object to clone.

Example

const originalJSON = { name: 'John', age: 30 };
const clonedJSON = deepCloneJSON(originalJSON);
console.log(clonedJSON.name); // Output: John

mergeJSONObjects(obj1, obj2) ⇒ any

Merge two JSON objects into a new one.

Kind: global function
Returns: any - The merged JSON object.

ParamTypeDescription
obj1anyThe first JSON object to merge.
obj2anyThe 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

filterJSONObject(jsonObj, filterFn) ⇒ Record.<string, any>

Filter a JSON object based on a callback function.

Kind: global function
Returns: Record.<string, any> - The filtered JSON object.

ParamTypeDescription
jsonObjRecord.<string, any>The JSON object to filter.
filterFnfunctionThe 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

mapJSONObjectValues(jsonObj, mapFn) ⇒ 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.

ParamTypeDescription
jsonObjRecord.<string, any>The JSON object to map.
mapFnfunctionThe 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

jsonToQueryString(jsonObj) ⇒ string

Convert a JSON object into URL query parameters.

Kind: global function
Returns: string - The URL query string.

ParamTypeDescription
jsonObjRecord.<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"

extractKeysFromJSON(jsonObj) ⇒ Array.<string>

Extract keys from a JSON object.

Kind: global function
Returns: Array.<string> - An array of keys from the JSON object.

ParamTypeDescription
jsonObjRecord.<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"]

isJSONObjectEmpty(jsonObj) ⇒ boolean

Check 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.

ParamTypeDescription
jsonObjRecord.<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

getNestedValue(jsonObj, path) ⇒ any | undefined

Get 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.

ParamTypeDescription
jsonObjRecord.<string, any>The JSON object to search within.
pathstringThe 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"

jsonToArray(jsonObj) ⇒ 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.

ParamTypeDescription
jsonObjRecord.<string, any>The JSON object to convert.

Example

const data = { name: 'John', age: 30 };
const valuesArray = jsonToArray(data);
console.log(valuesArray); // Output: ["John", 30]

arrayToJSONObject(arr, keyName) ⇒ 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.

ParamTypeDescription
arrArray.<any>The array of objects to convert.
keyNamestringThe 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" }
}

removeKeyFromJSON(jsonObj, keyToRemove) ⇒ 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.

ParamTypeDescription
jsonObjRecord.<string, any>The JSON object from which to remove the key.
keyToRemovestringThe 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

assertEqual(actual, expected)

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.
ParamTypeDescription
actualTThe actual value to compare.
expectedTThe expected value for comparison.

Example

assertEqual(5, 5); // No error is thrown
assertEqual("Hello", "World"); // Error: Values are not equal

assertNotEqual(actual, notExpected)

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.
ParamTypeDescription
actualTThe actual value to compare.
notExpectedTThe 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

assertTrue(expression, message)

Asserts that a given expression evaluates to true.

Kind: global function
Throws:

  • Error Throws an error if the expression evaluates to false.
ParamTypeDescription
expressionbooleanThe expression to evaluate.
messagestringAn 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

assertRaises(func, [expectedError], [message])

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.
ParamTypeDescription
funcfunctionThe function to be tested for raising an exception.
[expectedError]ErrorConstructorThe expected error constructor to check against.
[message]stringAn 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

assertNoRaises(func)

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.
ParamTypeDescription
funcfunctionThe 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

assertContains(iterable, element, [message])

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.
ParamTypeDescription
iterableIterable.<T>The iterable to search for the element.
elementTThe element to check for in the iterable.
[message]stringAn 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

assertNotContains(iterable, element, [message])

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.
ParamTypeDescription
iterableIterable.<T>The iterable to search for the element.
elementTThe element to check for absence in the iterable.
[message]stringAn 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

assertSubset(subset, superset, [message])

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.
ParamTypeDescription
subsetIterable.<T>The iterable that should be a subset.
supersetIterable.<T>The iterable that should contain the subset.
[message]stringAn 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

assertAlmostEqual(actual, expected, [tolerance], [message])

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.
ParamTypeDefaultDescription
actualnumberThe actual number to compare.
expectednumberThe expected number for comparison.
[tolerance]number1e-9The tolerance within which the numbers are considered equal.
[message]stringAn 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

assertGreaterThan(actual, expected, [message])

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.
ParamTypeDescription
actualnumberThe actual number to compare.
expectednumberThe expected number for comparison.
[message]stringAn 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

assertLessThan(actual, expected, [message])

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.
ParamTypeDescription
actualnumberThe actual number to compare.
expectednumberThe expected number for comparison.
[message]stringAn 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

assertStringContains(actual, expectedSubstring, [message])

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.
ParamTypeDescription
actualstringThe actual string to check.
expectedSubstringstringThe substring that should be contained in the actual string.
[message]stringAn 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"

assertStringStartsWith(actual, expectedPrefix, [message])

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.
ParamTypeDescription
actualstringThe actual string to check.
expectedPrefixstringThe prefix that should be at the beginning of the actual string.
[message]stringAn 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"

assertStringEndsWith(actual, expectedSuffix, [message])

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.
ParamTypeDescription
actualstringThe actual string to check.
expectedSuffixstringThe suffix that should be at the end of the actual string.
[message]stringAn 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"

assertFileExists(path, [message])

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.
ParamTypeDescription
pathstringThe path to the file to check.
[message]stringAn 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"

assertFileNotExists(path, [message])

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.
ParamTypeDescription
pathstringThe path to the file to check for non-existence.
[message]stringAn 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"

generateTestData(size) ⇒ 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.

ParamTypeDescription
sizenumberThe size of the dataset to generate.

Example

const testData = generateTestData(100); // Generates an array of 100 test data items.

assertCalledWith(mockFunction, ...args)

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.
ParamTypeDescription
mockFunctionfunctionThe mock function to check.
...argsanyThe 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")

assertCalledWith~calledWithExpectedArgs

The flag to track whether the mock function was called with the expected arguments.

Kind: inner property of assertCalledWith

measureExecutionTime(func, ...args) ⇒ number

Measures and logs the execution time of a function.

Kind: global function
Returns: number - The execution time of the function in milliseconds.

ParamTypeDescription
funcfunctionThe function to measure the execution time of.
...argsanyThe 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`);

assertExecutionTimeLessThan(func, maxTime, [message])

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.
ParamTypeDescription
funcfunctionThe function to be executed and timed.
maxTimenumberThe maximum allowed execution time in milliseconds.
[message]stringAn 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

assertHttpStatus(url, expectedStatusCode, [message])

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.
ParamTypeDescription
urlstringThe URL to send the HTTP request to.
expectedStatusCodenumberThe expected HTTP status code to compare with the response.
[message]stringAn 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

assertWebPageContains(url, expectedContent, [message])

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.
ParamTypeDescription
urlstringThe URL to retrieve the web page from.
expectedContentstringThe expected content that should be found in the web page.
[message]stringAn 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'

generateRandomData(dataType, size) ⇒ 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.

ParamTypeDescription
dataTypestringThe type of random data to generate (e.g., 'string', 'number', 'boolean').
sizenumberThe 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

compareData(actual, expected, [tolerance]) ⇒ boolean

Compares two data structures for equality, ignoring minor differences.

Kind: global function
Returns: boolean - true if the data structures are considered equal; otherwise, false.

ParamTypeDefaultDescription
actualanyThe actual data structure to compare.
expectedanyThe expected data structure to compare against.
[tolerance]number1e-6A 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

cleanData(data, elementsToRemove) ⇒ any

Cleans a data structure by removing specified elements.

Kind: global function
Returns: any - The cleaned data structure with specified elements removed.

ParamTypeDescription
dataanyThe data structure to clean.
elementsToRemoveArray.<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

testConcurrentOperations(operations) ⇒ 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.

ParamTypeDescription
operationsArrayAn 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]);

assertNetworkConnection(host, port) ⇒ 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.

ParamTypeDescription
hoststringThe host to connect to (e.g., a domain or IP address).
portnumberThe 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);
}

simulateNetworkFailure(host, port) ⇒ 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.

ParamTypeDescription
hoststringThe host to simulate a network failure for (e.g., a domain or IP address).
portnumberThe 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);
}

testParallelFunctions(functions) ⇒ 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.

ParamTypeDescription
functionsArrayAn 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.

generateURL(address, base) ⇒ URL | undefined

Generates 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.

ParamTypeDescription
addressstringThe string representing the URL address.
basestringThe 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");

urlHash(address) ⇒ string | undefined

Extracts 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.

ParamTypeDescription
addressstringThe 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

urlHost(address) ⇒ string | undefined

Extracts 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.

ParamTypeDescription
addressstringThe 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

urlHref(address) ⇒ string | undefined

Retrieves 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.

ParamTypeDescription
addressstringThe 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

urlOrigin(address) ⇒ string | undefined

Retrieves 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.

ParamTypeDescription
addressstringThe 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

urlPassword(address) ⇒ string | undefined

Retrieves 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.

ParamTypeDescription
addressstringThe 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

urlPathname(address) ⇒ string | undefined

Retrieves 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.

ParamTypeDescription
addressstringThe 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

urlPort(address) ⇒ string | undefined

Retrieves 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.

ParamTypeDescription
addressstringThe 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

urlProtocol(address) ⇒ string | undefined

Retrieves 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.

ParamTypeDescription
addressstringThe 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

urlSearch(address) ⇒ string | undefined

Retrieves 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.

ParamTypeDescription
addressstringThe 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

urlSearchParams(address, param) ⇒ string | null | undefined

Retrieves 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.

ParamTypeDescription
addressstringThe string representing the URL address.
paramstringThe 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)

urlUsername(address) ⇒ string | undefined

Retrieves 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.

ParamTypeDescription
addressstringThe 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

createObjectURL(file) ⇒ string | undefined

Creates 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.

ParamTypeDescription
fileFileThe 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)

revokeObjectURL(url) ⇒ void

Revokes 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.

ParamTypeDescription
urlstringThe object URL to revoke.

Example

Example:
const objectUrl = createObjectURL(someFile);
revokeObjectURL(objectUrl);

url2JSON(address) ⇒ string | undefined

Converts 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.

ParamTypeDescription
addressstringThe 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

url2String(address) ⇒ string | undefined

Converts 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.

ParamTypeDescription
addressstringThe 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

isEmailValid(email) ⇒ boolean

Checks 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.

ParamTypeDescription
emailstringThe 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

isPasswordValid(password, upper, lower, num, special, length) ⇒ boolean

Checks 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).

ParamTypeDefaultDescription
passwordstringThe password to validate.
upperbooleantrueWhether the password must contain an uppercase letter.
lowerbooleantrueWhether the password must contain a lowercase letter.
numbooleantrueWhether the password must contain a digit.
specialbooleantrueWhether the password must contain a special character.
lengthbooleantrueWhether 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

isPhoneValid(phone) ⇒ boolean

Checks 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").

ParamTypeDescription
phonestringThe 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

isURLValid(address, base) ⇒ boolean

Checks 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.

ParamTypeDescription
addressstringThe string to validate as a URL.
basestringThe 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

isUsernameValid(username) ⇒ boolean

Checks 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.

ParamTypeDescription
usernamestringThe 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

isInteger(num) ⇒ boolean

Checks 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.

ParamTypeDescription
numnumberThe number to check.

Example

Example 1:
const result1: boolean = isInteger(42);
Returns true

Example 2:
const result2: boolean = isInteger(3.14);
Returns false

isFinite(num) ⇒ boolean

Checks 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.

ParamTypeDescription
numnumberThe number to check.

Example

Example 1:
const result1: boolean = isFinite(42);
Returns true

Example 2:
const result2: boolean = isFinite(Infinity);
Returns false

isNan(num) ⇒ boolean

Checks 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.

ParamTypeDescription
numnumberThe number to check.

Example

Example 1:
const result1: boolean = isNaN(NaN);
Returns true

Example 2:
const result2: boolean = isNaN(42);
Returns false

isSafeInteger(num) ⇒ boolean

Checks 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.

ParamTypeDescription
numnumberThe number to check.

Example

Example 1:
const result1: boolean = isSafeInteger(42);
Returns true

Example 2:
const result2: boolean = isSafeInteger(2 ** 53);
Returns false

isString(value) ⇒ boolean

Checks 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".

ParamTypeDescription
valuestringThe value to check.

Example

Example 1:
const result1: boolean = isString("Hello, World!");
Returns true

Example 2:
const result2: boolean = isString(42);
Returns false

isDecimal(num) ⇒ boolean

Checks 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.

ParamTypeDescription
numnumberThe number to check.

Example

Example 1:
const result1: boolean = isDecimal(3.14);
Returns true

Example 2:
const result2: boolean = isDecimal(42);
Returns false

isBoolean(value) ⇒ boolean

Checks 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.

ParamTypeDescription
valuebooleanThe value to check.

Example

Example 1:
const result1: boolean = isBoolean(true);
Returns true

Example 2:
const result2: boolean = isBoolean("false");
Returns false

isUpperCase(text) ⇒ boolean

Checks 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.

ParamTypeDescription
textstringThe string to check.

Example

Example 1:
const result1: boolean = isUpperCase("HELLO");
Returns true

Example 2:
const result2: boolean = isUpperCase("Hello");
Returns false

isLowerCase(text) ⇒ boolean

Checks 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.

ParamTypeDescription
textstringThe string to check.

Example

Example 1:
const result1: boolean = isLowerCase("hello");
Returns true

Example 2:
const result2: boolean = isLowerCase("Hello");
Returns false

isAlpha(text) ⇒ boolean

Checks 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.

ParamTypeDescription
textstringThe string to check.

Example

Example 1:
const result1: boolean = isAlpha("abcXYZ");
Returns true

Example 2:
const result2: boolean = isAlpha("Hello123");
Returns false

isNumeric(text) ⇒ boolean

Checks 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.

ParamTypeDescription
textstringThe string to check.

Example

Example 1:
const result1: boolean = isNumeric("12345");
Returns true

Example 2:
const result2: boolean = isNumeric("42a");
Returns false

isAlphaNumeric(text) ⇒ boolean

Checks 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.

ParamTypeDescription
textstringThe string to check.

Example

Example 1:
const result1: boolean = isAlphaNumeric("Hello123");
Returns true

Example 2:
const result2: boolean = isAlphaNumeric("Hello@123");
Returns false

isStrictAlphaNumeric(text) ⇒ boolean

Checks 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.

ParamTypeDescription
textstringThe string to check.

Example

Example 1:
const result1: boolean = isStrictAlphaNumeric("Hello123");
Returns true

Example 2:
const result2: boolean = isStrictAlphaNumeric("123");
Returns false

isCamelCase(text) ⇒ boolean

Checks 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.

ParamTypeDescription
textstringThe string to check.

Example

Example 1:
const result1: boolean = isCamelCase("helloWorld");
Returns true

Example 2:
const result2: boolean = isCamelCase("hello_world");
Returns false

isPascalCase(text) ⇒ boolean

Checks 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.

ParamTypeDescription
textstringThe string to check.

Example

Example 1:
const result1: boolean = isPascalCase("HelloWorld");
Returns true

Example 2:
const result2: boolean = isPascalCase("helloWorld");
Returns false

isSnakeCase(text) ⇒ boolean

Checks 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.

ParamTypeDescription
textstringThe string to check.

Example

Example 1:
const result1: boolean = isSnakeCase("hello_world");
Returns true

Example 2:
const result2: boolean = isSnakeCase("HelloWorld");
Returns false

isDateOfBirthValid(dateOfBirth) ⇒ boolean

Checks 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.

ParamTypeDescription
dateOfBirthstringThe date of birth to validate (yyyy-mm-dd format).

Example

const isValid = isDateOfBirthValid("1990-01-15"); // Returns true

isPostalCodeValid(postalCode) ⇒ boolean

Checks 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.

ParamTypeDescription
postalCodestringThe postal code to validate.

Example

const isValid = isPostalCodeValid("12345"); // Returns true

isCreditCardValid(creditCardNumber) ⇒ boolean

Checks 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.

ParamTypeDescription
creditCardNumberstringThe credit card number to validate.

Example

const isValid = isCreditCardValid("1234567890123456"); // Returns true

isZIPCodeValid(zipCode) ⇒ boolean

Checks 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.

ParamTypeDescription
zipCodestringThe ZIP code to validate.

Example

const isValid = isZIPCodeValid("12345"); // Returns true

isSSNValid(ssn) ⇒ boolean

Checks if a social security number (SSN) is in a valid format.

Kind: global function
Returns: boolean - True if the SSN is valid, otherwise false.

ParamTypeDescription
ssnstringThe social security number to validate.

Example

const isValid = isSSNValid("123-45-6789"); // Returns true

isIPValid(ipAddress) ⇒ boolean

Checks 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.

ParamTypeDescription
ipAddressstringThe IP address to validate.

Example

const isValid = isIPValid("192.168.0.1"); // Returns true

isCreditCardExpirationValid(expirationDate) ⇒ boolean

Checks 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.

ParamTypeDescription
expirationDatestringThe credit card expiration date to validate (MM/YYYY format).

Example

const isValid = isCreditCardExpirationValid("12/2025"); // Returns true

isSecurityCodeValid(securityCode, cardType) ⇒ boolean

Checks 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.

ParamTypeDescription
securityCodestringThe security code to validate.
cardTypestringThe credit card type (e.g., "Visa", "MasterCard").

Example

const isValid = isSecurityCodeValid("123", "Visa"); // Returns true

isFileExtensionValid(fileName, allowedExtensions) ⇒ boolean

Checks 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.

ParamTypeDescription
fileNamestringThe file name to validate.
allowedExtensionsArray.<string>An array of allowed file extensions (e.g., ["jpg", "png"]).

Example

const isValid = isFileExtensionValid("document.pdf", ["pdf", "doc", "docx"]); // Returns true

isOTPValid(otp, userSecret) ⇒ boolean

Checks 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.

ParamTypeDescription
otpstringThe one-time password entered by the user.
userSecretstringThe user's secret used for OTP generation.

Example

const isValid = isOTPValid("123456", "secret123"); // Returns true

isPINValid(pin, userPin) ⇒ boolean

Checks 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.

ParamTypeDescription
pinstringThe PIN entered by the user.
userPinstringThe user's stored PIN.

Example

const isValid = isPINValid("1234", "5678"); // Returns false

generateOTP(secret) ⇒ string

Generates a one-time password (OTP) using the provided secret.

Kind: global function
Returns: string - The generated OTP.

ParamTypeDescription
secretstringThe secret used for OTP generation.

isFullNameValid(fullName) ⇒ boolean

Checks 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.

ParamTypeDescription
fullNamestringThe full name to validate.

Example

const isValid = isFullNameValid("John Doe"); // Returns true

isAddressValid(address) ⇒ boolean

Checks 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.

ParamTypeDescription
addressstringThe address to validate.

Example

const isValid = isAddressValid("123 Main St, New York, NY 10001"); // Returns true

isCityValid(city) ⇒ boolean

Checks 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.

ParamTypeDescription
citystringThe city name to validate.

Example

const isValid = isCityValid("New York"); // Returns true

isStateValid(state) ⇒ boolean

Checks 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.

ParamTypeDescription
statestringThe state abbreviation or name to validate.

Example

const isValid = isStateValid("NY"); // Returns true

isAgeValid(age, minAge, maxAge) ⇒ boolean

Checks if an age is within the specified range.

Kind: global function
Returns: boolean - True if the age is within the specified range, otherwise false.

ParamTypeDefaultDescription
agenumberThe age to validate.
minAgenumber0The minimum allowed age.
maxAgenumber120The maximum allowed age.

Example

const isValid = isAgeValid(25, 18, 65); // Returns true

isGenderValid(gender) ⇒ boolean

Checks 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.

ParamTypeDescription
genderstringThe gender value to validate.

Example

const isValid = isGenderValid("Male"); // Returns true

isCreditCardTypeValid(cardType) ⇒ boolean

Checks 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.

ParamTypeDescription
cardTypestringThe credit card type to validate.

Example

const isValid = isCreditCardTypeValid("Visa"); // Returns true

isISBNValid(isbn) ⇒ boolean

Checks if an International Standard Book Number (ISBN) follows a valid format.

Kind: global function
Returns: boolean - True if the ISBN is valid, otherwise false.

ParamTypeDescription
isbnstringThe ISBN to validate.

Example

const isValid = isISBNValid("978-3-16-148410-0"); // Returns true

isCurrencyValid(currencyAmount) ⇒ boolean

Checks 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.

ParamTypeDescription
currencyAmountstringThe currency amount to validate.

Example

const isValid = isCurrencyValid("$100.50"); // Returns true

isTimeValid(time) ⇒ boolean

Checks 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.

ParamTypeDescription
timestringThe time value to validate.

Example

const isValid = isTimeValid("12:34:56"); // Returns true

isURLPathValid(urlPath) ⇒ boolean

Checks 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.

ParamTypeDescription
urlPathstringThe URL path to validate.

Example

const isValid = isURLPathValid("/products/category"); // Returns true

isHexColorValid(hexColor) ⇒ boolean

Checks 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.

ParamTypeDescription
hexColorstringThe hexadecimal color code to validate.

Example

const isValid = isHexColorValid("#FFA500"); // Returns true

isIMEINumberValid(imei) ⇒ boolean

Checks if the International Mobile Equipment Identity (IMEI) number is valid.

Kind: global function
Returns: boolean - True if the IMEI number is valid, otherwise false.

ParamTypeDescription
imeistringThe IMEI number to validate.

Example

const isValid = isIMEINumberValid("123456789012345"); // Returns true

isMACAddressValid(macAddress) ⇒ boolean

Checks 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.

ParamTypeDescription
macAddressstringThe MAC address to validate.

Example

const isValid = isMACAddressValid("00:1A:2B:3C:4D:5E"); // Returns true

isDomainNameValid(domainName) ⇒ boolean

Checks 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.

ParamTypeDescription
domainNamestringThe domain name to validate.

Example

const isValid = isDomainNameValid("example.com"); // Returns true

CompressionOptions : Object

Represents options for compression and decompression.

Kind: global typedef
Properties

NameTypeDefaultDescription
[algorithm]string"&quot;inflate&quot;"The compression or decompression algorithm to use ("inflate" or "deflate").

Keywords

utils

FAQs

Package last updated on 12 Oct 2025

Did you know?

Socket

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.

Install

Related posts