Represents a singly linked list.
Kind: global class
-
LinkedList
-
.size ⇒
number
- .append(value)
- .prepend(value)
-
.insertAfter(value, target) ⇒
boolean
-
.remove(value) ⇒
boolean
-
.find(value) ⇒
T
|null
-
.isEmpty() ⇒
boolean
-
.toArray() ⇒
Array.<T>
- .clear()
-
.size ⇒
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
Appends a new element to the end of the linked list.
Kind: instance method of LinkedList
Param | Type | Description |
---|---|---|
value | T |
The value to append. |
Example
const list = new LinkedList();
list.append(1);
list.append(2);
console.log(list.toArray()); // Output: [1, 2]
Prepends a new element to the beginning of the linked list.
Kind: instance method of LinkedList
Param | Type | Description |
---|---|---|
value | T |
The value to prepend. |
Example
const list = new LinkedList();
list.prepend(1);
list.prepend(2);
console.log(list.toArray()); // Output: [2, 1]
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.
Param | Type | Description |
---|---|---|
value | T |
The value to insert. |
target | T |
The element after which the new value should be inserted. |
Example
const list = new LinkedList();
list.append(1);
list.append(2);
list.insertAfter(3, 1);
console.log(list.toArray()); // Output: [1, 3, 2]
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.
Param | Type | Description |
---|---|---|
value | T |
The value to remove. |
Example
const list = new LinkedList();
list.append(1);
list.append(2);
list.remove(1);
console.log(list.toArray()); // Output: [2]
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.
Param | Type | Description |
---|---|---|
value | T |
The value to find. |
Example
const list = new LinkedList();
list.append(1);
list.append(2);
const foundValue = list.find(2);
console.log(foundValue); // Output: 2
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
Converts the linked list to an array.
Kind: instance method of LinkedList
Returns: Array.<T>
- An array containing all elements of the linked list in order.
Example
const list = new LinkedList();
list.append(1);
list.append(2);
const array = list.toArray();
console.log(array); // Output: [1, 2]
Clears all elements from the linked list.
Kind: instance method of LinkedList
Example
const list = new LinkedList();
list.append(1);
list.append(2);
list.clear();
console.log(list.toArray()); // Output: []
console.log(list.size); // Output: 0
Represents a stack data structure.
Kind: global class
-
Stack
- .push(element)
-
.pop() ⇒
T
|undefined
-
.peek() ⇒
T
|undefined
-
.isEmpty() ⇒
boolean
-
.size() ⇒
number
- .clear()
-
.toArray() ⇒
Array.<T>
Pushes an element onto the top of the stack.
Kind: instance method of Stack
Param | Type | Description |
---|---|---|
element | T |
The element to push onto the stack. |
Example
const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.toArray()); // Output: [1, 2]
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]
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]
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
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
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
Converts the stack to an array.
Kind: instance method of Stack
Returns: Array.<T>
- An array containing all elements of the stack in order from top to bottom.
Example
const stack = new Stack();
stack.push(1);
stack.push(2);
const array = stack.toArray();
console.log(array); // Output: [2, 1]
Represents a queue data structure.
Kind: global class
-
Queue
- .enqueue(element)
-
.dequeue() ⇒
T
|undefined
-
.peek() ⇒
T
|undefined
-
.isEmpty() ⇒
boolean
-
.size() ⇒
number
- .clear()
-
.toArray() ⇒
Array.<T>
Adds an element to the back of the queue.
Kind: instance method of Queue
Param | Type | Description |
---|---|---|
element | T |
The element to enqueue. |
Example
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.toArray()); // Output: [1, 2]
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]
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]
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
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
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
Converts the queue to an array.
Kind: instance method of Queue
Returns: Array.<T>
- An array containing all elements of the queue in order from front to back.
Example
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
const array = queue.toArray();
console.log(array); // Output: [1, 2]
Represents a node in a binary search tree.
Represents a binary search tree.
Kind: global class
-
BinarySearchTree
- .insert(value)
- .delete(value)
-
.find(value) ⇒
boolean
-
.getMin() ⇒
T
|null
-
.getMax() ⇒
T
|null
-
.getHeight() ⇒
number
-
.traverseInOrder() ⇒
Array.<T>
-
.traversePreOrder() ⇒
Array.<T>
-
.traversePostOrder() ⇒
Array.<T>
Inserts a new element into the binary search tree.
Kind: instance method of BinarySearchTree
Param | Type | Description |
---|---|---|
value | T |
The value to insert. |
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.find(3)); // Output: true
console.log(bst.find(6)); // Output: false
Deletes an element from the binary search tree.
Kind: instance method of BinarySearchTree
Param | Type | Description |
---|---|---|
value | T |
The value to delete. |
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
bst.delete(3);
console.log(bst.find(3)); // Output: false
Finds an element in the binary search tree.
Kind: instance method of BinarySearchTree
Returns: boolean
- true
if the element is found, false
otherwise.
Param | Type | Description |
---|---|---|
value | T |
The value to find. |
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.find(3)); // Output: true
console.log(bst.find(6)); // Output: false
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
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
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
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]
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]
Traverses the binary search tree in post-order and returns the elements in an array.
Kind: instance method of BinarySearchTree
Returns: Array.<T>
- An array containing elements of the tree in post-order.
Example
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
console.log(bst.traversePostOrder()); // Output: [3, 8, 5]
Represents a vertex in an undirected graph.
Represents an undirected graph.
Kind: global class
-
UndirectedGraph
- .addVertex(value)
- .removeVertex(value)
- .addEdge(value1, value2)
- .removeEdge(value1, value2)
-
.hasVertex(value) ⇒
boolean
-
.hasEdge(value1, value2) ⇒
boolean
-
.getNeighbors(value) ⇒
Array.<T>
Adds a new vertex to the graph.
Kind: instance method of UndirectedGraph
Param | Type | Description |
---|---|---|
value | T |
The value to associate with the new vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
Removes a vertex and all its edges from the graph.
Kind: instance method of UndirectedGraph
Param | Type | Description |
---|---|---|
value | T |
The value associated with the vertex to remove. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');
graph.removeVertex('A');
Adds an edge between two vertices in the graph.
Kind: instance method of UndirectedGraph
Param | Type | Description |
---|---|---|
value1 | T |
The value associated with the first vertex. |
value2 | T |
The value associated with the second vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');
Removes an edge between two vertices in the graph.
Kind: instance method of UndirectedGraph
Param | Type | Description |
---|---|---|
value1 | T |
The value associated with the first vertex. |
value2 | T |
The value associated with the second vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');
graph.removeEdge('A', 'B');
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.
Param | Type | Description |
---|---|---|
value | T |
The value associated with the vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
console.log(graph.hasVertex('A')); // Output: true
console.log(graph.hasVertex('B')); // Output: false
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.
Param | Type | Description |
---|---|---|
value1 | T |
The value associated with the first vertex. |
value2 | T |
The value associated with the second vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');
console.log(graph.hasEdge('A', 'B')); // Output: true
console.log(graph.hasEdge('A', 'C')); // Output: false
Gets an array of neighbors for a given vertex.
Kind: instance method of UndirectedGraph
Returns: Array.<T>
- An array of neighbor values.
Param | Type | Description |
---|---|---|
value | T |
The value associated with the vertex. |
Example
const graph = new UndirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');
graph.addEdge('A', 'B');
graph.addEdge('A', 'C');
console.log(graph.getNeighbors('A')); // Output: ['B', 'C']
Represents a key-value pair in a hash table.
Represents a hash table.
Kind: global class
-
HashTable
- .put(key, value)
-
.get(key) ⇒
V
|undefined
- .remove(key)
-
.containsKey(key) ⇒
boolean
-
.keys() ⇒
Array.<K>
-
.values() ⇒
Array.<V>
Inserts a key-value pair into the hash table.
Kind: instance method of HashTable
Param | Type | Description |
---|---|---|
key | K |
The key to insert. |
value | V |
The value to insert. |
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
hashTable.put('banana', 8);
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.
Param | Type | Description |
---|---|---|
key | K |
The key to search for. |
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
console.log(hashTable.get('apple')); // Output: 5
console.log(hashTable.get('banana')); // Output: undefined
Removes a key-value pair associated with a key from the hash table.
Kind: instance method of HashTable
Param | Type | Description |
---|---|---|
key | K |
The key to remove. |
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
hashTable.remove('apple');
console.log(hashTable.get('apple')); // Output: undefined
Checks if the hash table contains a key.
Kind: instance method of HashTable
Returns: boolean
- true
if the key exists, false
otherwise.
Param | Type | Description |
---|---|---|
key | K |
The key to check. |
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
console.log(hashTable.containsKey('apple')); // Output: true
console.log(hashTable.containsKey('banana')); // Output: false
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']
Retrieves an array of values in the hash table.
Kind: instance method of HashTable
Returns: Array.<V>
- An array of values in the hash table.
Example
const hashTable = new HashTable<string, number>();
hashTable.put('apple', 5);
hashTable.put('banana', 8);
console.log(hashTable.values()); // Output: [5, 8]
Represents a node in a B-Tree.
Represents a node in a Trie.
Represents a Trie (prefix tree).
Kind: global class
-
Trie
- .insert(word)
-
.search(word) ⇒
boolean
-
.startsWith(prefix) ⇒
boolean
- .delete(word)
-
.autocomplete(prefix) ⇒
Array.<string>
Inserts a word into the Trie.
Kind: instance method of Trie
Param | Type | Description |
---|---|---|
word | string |
The word to insert. |
Example
const trie = new Trie();
trie.insert("apple");
trie.insert("app");
Searches for a word in the Trie.
Kind: instance method of Trie
Returns: boolean
- true
if the word is found, false
otherwise.
Param | Type | Description |
---|---|---|
word | string |
The word to search for. |
Example
const trie = new Trie();
trie.insert("apple");
console.log(trie.search("apple")); // Output: true
console.log(trie.search("app")); // Output: false
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.
Param | Type | Description |
---|---|---|
prefix | string |
The prefix to check. |
Example
const trie = new Trie();
trie.insert("apple");
console.log(trie.startsWith("app")); // Output: true
console.log(trie.startsWith("ban")); // Output: false
Deletes a word from the Trie.
Kind: instance method of Trie
Param | Type | Description |
---|---|---|
word | string |
The word to delete. |
Example
const trie = new Trie();
trie.insert("apple");
trie.delete("apple");
console.log(trie.search("apple")); // Output: false
Returns a list of words in the Trie that start with a given prefix.
Kind: instance method of Trie
Returns: Array.<string>
- An array of autocompleted words.
Param | Type | Description |
---|---|---|
prefix | string |
The prefix to autocomplete. |
Example
const trie = new Trie();
trie.insert("apple");
trie.insert("appetizer");
console.log(trie.autocomplete("app")); // Output: ["apple", "appetizer"]
console.log(trie.autocomplete("ban")); // Output: []
Represents a sparse matrix.
Kind: global class
Constructs a sparse matrix with the specified number of rows and columns.
Param | Type | Description |
---|---|---|
rows | number |
The number of rows in the matrix. |
cols | number |
The number of columns in the matrix. |
Example
const matrix = new SparseMatrix(3, 4);
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.
Param | Type | Description |
---|---|---|
row | number |
The row index (0-based). |
col | number |
The column index (0-based). |
Example
const matrix = new SparseMatrix(3, 4);
matrix.set(0, 1, 5);
console.log(matrix.get(0, 1)); // Output: 5
console.log(matrix.get(1, 2)); // Output: 0
Sets the value at the specified row and column in the matrix.
Kind: instance method of SparseMatrix
Param | Type | Description |
---|---|---|
row | number |
The row index (0-based). |
col | number |
The column index (0-based). |
value | number |
The value to set. |
Example
const matrix = new SparseMatrix(3, 4);
matrix.set(0, 1, 5);
console.log(matrix.get(0, 1)); // Output: 5
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.
Param | Type | Description |
---|---|---|
otherMatrix | SparseMatrix |
The matrix to add. |
Example
const matrixA = new SparseMatrix(2, 3);
matrixA.set(0, 1, 5);
const matrixB = new SparseMatrix(2, 3);
matrixB.set(0, 1, 3);
const result = matrixA.add(matrixB);
console.log(result.get(0, 1)); // Output: 8
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.
Param | Type | Description |
---|---|---|
otherMatrix | SparseMatrix |
The matrix to multiply by. |
Example
const matrixA = new SparseMatrix(2, 3);
matrixA.set(0, 1, 5);
const matrixB = new SparseMatrix(3, 2);
matrixB.set(1, 0, 3);
const result = matrixA.multiply(matrixB);
console.log(result.get(0, 0)); // Output: 15
Compresses the matrix by removing zero values.
Kind: instance method of SparseMatrix
Example
const matrix = new SparseMatrix(3, 4);
matrix.set(0, 1, 5);
matrix.set(1, 2, 0);
matrix.compress();
console.log(matrix.get(0, 1)); // Output: 5
console.log(matrix.get(1, 2)); // Output: 0
Represents a BitSet, a data structure for efficient manipulation of bits.
Kind: global class
-
BitSet
- new BitSet(size)
- .set(index)
- .clear(index)
- .toggle(index)
-
.test(index) ⇒
boolean
-
.countSetBits() ⇒
number
-
.findNextSetBit(startIndex) ⇒
number
Constructs a BitSet with the specified number of bits.
Param | Type | Description |
---|---|---|
size | number |
The number of bits in the BitSet. |
Example
const bitSet = new BitSet(10);
Sets the bit at the specified index to 1.
Kind: instance method of BitSet
Param | Type | Description |
---|---|---|
index | number |
The index of the bit to set. |
Example
const bitSet = new BitSet(10);
bitSet.set(3);
console.log(bitSet.test(3)); // Output: true
Clears the bit at the specified index (sets it to 0).
Kind: instance method of BitSet
Param | Type | Description |
---|---|---|
index | number |
The index of the bit to clear. |
Example
const bitSet = new BitSet(10);
bitSet.set(3);
bitSet.clear(3);
console.log(bitSet.test(3)); // Output: false
Toggles the bit at the specified index (flips its value).
Kind: instance method of BitSet
Param | Type | Description |
---|---|---|
index | number |
The index of the bit to toggle. |
Example
const bitSet = new BitSet(10);
bitSet.toggle(3);
console.log(bitSet.test(3)); // Output: true
bitSet.toggle(3);
console.log(bitSet.test(3)); // Output: false
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).
Param | Type | Description |
---|---|---|
index | number |
The index of the bit to test. |
Example
const bitSet = new BitSet(10);
bitSet.set(3);
console.log(bitSet.test(3)); // Output: true
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
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.
Param | Type | Description |
---|---|---|
startIndex | number |
The starting index (inclusive). |
Example
const bitSet = new BitSet(10);
bitSet.set(3);
bitSet.set(5);
console.log(bitSet.findNextSetBit(0)); // Output: 3
console.log(bitSet.findNextSetBit(4)); // Output: 5
console.log(bitSet.findNextSetBit(6)); // Output: -1
Represents a Circular Buffer, a data structure for managing a fixed-size buffer with efficient enqueue and dequeue operations.
Kind: global class
-
CircularBuffer
- new CircularBuffer(size)
- .enqueue(element)
-
.dequeue() ⇒
T
-
.isFull() ⇒
boolean
-
.isEmpty() ⇒
boolean
-
.peek() ⇒
T
- .clear()
Constructs a Circular Buffer with the specified size.
Param | Type | Description |
---|---|---|
size | number |
The maximum size of the buffer. |
Example
const circularBuffer = new CircularBuffer<number>(5);
Enqueues an element at the rear of the Circular Buffer.
Kind: instance method of CircularBuffer
Param | Type | Description |
---|---|---|
element | T |
The element to enqueue. |
Example
const circularBuffer = new CircularBuffer<number>(5);
circularBuffer.enqueue(1);
circularBuffer.enqueue(2);
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
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
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
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
Clears all elements from the Circular Buffer.
Kind: instance method of CircularBuffer
Example
const circularBuffer = new CircularBuffer<number>(3);
circularBuffer.enqueue(1);
circularBuffer.enqueue(2);
circularBuffer.clear();
console.log(circularBuffer.isEmpty()); // Output: true
Represents a node in a self-adjusting list (Splay Tree).
Represents a self-adjusting list (Splay Tree).
Kind: global class
Performs a splay operation on the tree to bring the specified element to the root.
Kind: instance method of SelfAdjustingList
Param | Type | Description |
---|---|---|
element | T |
The element to splay. |
Example
const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.splay(1);
Inserts an element into the self-adjusting list.
Kind: instance method of SelfAdjustingList
Param | Type | Description |
---|---|---|
element | T |
The element to insert. |
Example
const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.insert(2);
Moves the specified element to the front of the self-adjusting list.
Kind: instance method of SelfAdjustingList
Param | Type | Description |
---|---|---|
element | T |
The element to move to the front. |
Example
const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.insert(2);
splayTree.moveToFront(1);
Inserts an element after a specified element in the self-adjusting list.
Kind: instance method of SelfAdjustingList
Param | Type | Description |
---|---|---|
target | T |
The element after which to insert. |
element | T |
The element to insert. |
Example
const splayTree = new SelfAdjustingList<number>();
splayTree.insert(1);
splayTree.insert(3);
splayTree.insertAfter(1, 2);
This file contains all Wavefuel's async utility functions
Kind: global variable
Author: Mr.Blue
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White
This file contains all Wavefuel's file utility functions
Kind: global variable
Author: Mr.Blue
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White
This file contains all Wavefuel's test utility functions
Kind: global variable
Author: Mr.Blue
This file contains all Wavefuel's data utility functions
Kind: global variable
Author: Mr.White MrBlue
In-memory cache for storing cached API responses. You may need to adjust the cache implementation based on your needs.
Sends a GET request to the specified URL and returns the response data.
Kind: global function
Returns: Promise.<T>
- A Promise that resolves with the response data of type T.
Throws:
-
Error
If an error occurs during the request.
Param | Type | Description |
---|---|---|
url | string |
The URL to send the GET request to. |
Sends a POST request to the specified URL with the provided data and returns the response data.
Kind: global function
Returns: Promise.<T>
- A Promise that resolves with the response data of type T.
Throws:
-
Error
If an error occurs during the request.
Param | Type | Description |
---|---|---|
url | string |
The URL to send the POST request to. |
data | Record.<string, any> |
The data to send in the request body. |
Sends a PUT request to the specified URL with the provided data and returns the response data.
Kind: global function
Returns: Promise.<T>
- A Promise that resolves with the response data of type T.
Throws:
-
Error
If an error occurs during the request.
Param | Type | Description |
---|---|---|
url | string |
The URL to send the PUT request to. |
data | Record.<string, any> |
The data to send in the request body. |
Sends a PATCH request to the specified URL with the provided data and returns the response data.
Kind: global function
Returns: Promise.<T>
- A Promise that resolves with the response data of type T.
Throws:
-
Error
If an error occurs during the request.
Param | Type | Description |
---|---|---|
url | string |
The URL to send the PATCH request to. |
data | Record.<string, any> |
The data to send in the request body. |
Sends a DELETE request to the specified URL and returns the response data.
Kind: global function
Returns: Promise.<T>
- A Promise that resolves with the response data of type T.
Throws:
-
Error
If an error occurs during the request.
Param | Type | Description |
---|---|---|
url | string |
The URL to send the DELETE request to. |
Sends a HEAD request to the specified URL and returns the response headers.
Kind: global function
Returns: Promise.<Headers>
- A Promise that resolves with the response headers as a Headers object.
Throws:
-
Error
If an error occurs during the request.
Param | Type | Description |
---|---|---|
url | string |
The URL to send the HEAD request to. |
Sends a custom HTTP request to the specified URL with the given options and returns the response data or headers.
Kind: global function
Returns: Promise.<T>
- A Promise that resolves with the response data of type T or Headers if no body is expected.
Throws:
-
Error
If an error occurs during the request.
Param | Type | Description |
---|---|---|
url | string |
The URL to send the custom request to. |
options | RequestInit |
The options for the custom request, including method, headers, body, etc. |
Example
Sending a custom POST request with JSON body
const apiUrl = 'https://api.example.com/custom';
const customOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'value' }),
};
sendCustomRequest<{ message: string }>(apiUrl, customOptions)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
});
Serializes an object into a query string format for use in URL parameters.
Kind: global function
Returns: string
- The serialized query string.
Param | Type | Description |
---|---|---|
data | Record.<string, any> |
The object to be serialized into a query string. |
Example
Serialize an object into a query string
const data = { name: 'John', age: 30 };
const queryString = serializeData(data);
console.log(queryString); // Output: "name=John&age=30"
Deserializes a query string into an object.
Kind: global function
Returns: Record.<string, any>
- The deserialized object.
Param | Type | Description |
---|---|---|
queryString | string |
The query string to be deserialized. |
Example
Deserialize a query string into an object
const queryString = 'name=John&age=30';
const deserializedData = deserializeData(queryString);
console.log(deserializedData); // Output: { name: 'John', age: '30' }
Converts an XML string into a JSON object using inbuilt functions.
Kind: global function
Returns: object
- The JSON object.
Param | Type | Description |
---|---|---|
xmlString | string |
The XML string to be converted. |
Example
Convert an XML string into a JSON object
const xmlString = '<root><name>John</name><age>30</age></root>';
const jsonObject = convertXMLToJSON(xmlString);
console.log(jsonObject); // Output: { root: { name: 'John', age: '30' } }
Converts a CSV string into a JSON array.
Kind: global function
Returns: Array.<object>
- An array of JSON objects representing the CSV data.
Param | Type | Description |
---|---|---|
csvString | string |
The CSV string to be converted. |
delimiter | string |
The delimiter used in the CSV (e.g., ',' or ';'). |
Example
Convert a CSV string into a JSON array
const csvString = 'Name, Age, City\nJohn, 30, New York\nAlice, 25, Los Angeles';
const jsonArray = convertCSVToJSON(csvString, ',');
console.log(jsonArray);
Output: [
{ Name: 'John', Age: '30', City: 'New York' },
{ Name: 'Alice', Age: '25', City: 'Los Angeles' }
]
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.
Param | Type | Description |
---|---|---|
data | object |
The data object to be formatted. |
Example
Format a data object for display
const data = { name: 'John', age: 30, city: 'New York' };
const formattedData = formatDataForDisplay(data);
console.log(formattedData);
Output: "Name: John\nAge: 30\nCity: New York"
Handles an HTTP response, parsing the data and handling different status codes.
Kind: global function
Returns: Promise.<any>
- A Promise that resolves with the parsed response data.
Throws:
-
Error
If an error occurs during response handling.
Param | Type | Description |
---|---|---|
response | Response |
The HTTP response object. |
Example
Handle an HTTP response and parse the data
const apiUrl = 'https://api.example.com/data';
fetch(apiUrl)
.then(handleResponse)
.then((data) => {
console.log(data); // Parsed response data
})
.catch((error) => {
console.error(error);
});
Paginates a list of items and returns a specific page of results.
Kind: global function
Returns: Array.<any>
- The paginated page of results.
Param | Type | Description |
---|---|---|
items | Array.<any> |
The list of items to paginate. |
pageNumber | number |
The page number to retrieve (1-based index). |
pageSize | number |
The number of items per page. |
Example
Paginate a list of items
const itemList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const page = paginateResults(itemList, 2, 3);
console.log(page); // Output: [4, 5, 6]
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.
Param | Type | Description |
---|---|---|
baseUrl | string |
The base URL of the resource. |
currentPage | number |
The current page number (1-based index). |
pageSize | number |
The number of items per page. |
totalItems | number |
The total number of items across all pages. |
Example
Generate a link to the next page of results
const baseUrl = 'https://api.example.com/resource?page=';
const currentPage = 2;
const pageSize = 10;
const totalItems = 35;
const nextPageLink = getNextPageLink(baseUrl, currentPage, pageSize, totalItems);
console.log(nextPageLink);
Output: "https://api.example.com/resource?page=3"
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.
Param | Type | Description |
---|---|---|
baseUrl | string |
The base URL of the resource. |
currentPage | number |
The current page number (1-based index). |
pageSize | number |
The number of items per page. |
Example
Generate a link to the previous page of results
const baseUrl = 'https://api.example.com/resource?page=';
const currentPage = 3;
const pageSize = 10;
const previousPageLink = getPreviousPageLink(baseUrl, currentPage, pageSize);
console.log(previousPageLink);
Output: "https://api.example.com/resource?page=2"
Calculates the total number of pages required to paginate a list of items.
Kind: global function
Returns: number
- The total number of pages.
Param | Type | Description |
---|---|---|
totalItems | number |
The total number of items to paginate. |
pageSize | number |
The number of items per page. |
Example
Calculate the total number of pages for pagination
const totalItems = 35;
const pageSize = 10;
const totalPages = calculateTotalPages(totalItems, pageSize);
console.log(totalPages); // Output: 4
Handles API errors by checking the response and parsing error messages.
Kind: global function
Returns: Promise.<void>
- A Promise that resolves if there are no errors, or rejects with an error message.
Param | Type | Description |
---|---|---|
response | Response |
The HTTP response object from the API request. |
Example
Handle API errors when making a fetch request
const apiUrl = 'https://api.example.com/data';
fetch(apiUrl)
.then(handleAPIErrors)
.then((data) => {
console.log(data); // API response data
})
.catch((error) => {
console.error(error); // Handle API error
});
Handles rate limit exceeded errors by implementing rate limiting logic.
Kind: global function
Returns: Promise.<void>
- A Promise that resolves after waiting for the specified time.
Param | Type | Description |
---|---|---|
retryAfterSeconds | number |
The number of seconds to wait before retrying the request. |
Example
Handle rate limit exceeded error and retry the request
const retryAfterSeconds = 60; // Example: Retry after 1 minute
handleRateLimitExceeded(retryAfterSeconds)
.then(() => {
// Retry the API request here
console.log('Retrying the request after rate limit exceeded error.');
})
.catch((error) => {
console.error(error); // Handle error if waiting fails
});
Handles timeout errors by implementing timeout logic.
Kind: global function
Returns: Promise.<void>
- A Promise that resolves after waiting for the specified time.
Param | Type | Description |
---|---|---|
timeoutMilliseconds | number |
The maximum time to wait before triggering the timeout. |
Example
Handle timeout error and retry the operation
const timeoutMilliseconds = 5000; // Example: 5 seconds
handleTimeoutError(timeoutMilliseconds)
.then(() => {
// Handle the timeout error by retrying the operation or taking other actions.
console.log('Operation timed out.');
})
.catch((error) => {
console.error(error); // Handle error if waiting fails
});
Generates authentication headers for HTTP Basic Authentication.
Kind: global function
Returns: Headers
- Authentication headers.
Param | Type | Description |
---|---|---|
username | string |
The username for authentication. |
password | string |
The password for authentication. |
Example
Generate authentication headers for Basic Authentication
const username = 'myUsername';
const password = 'myPassword';
const headers = generateAuthHeaders(username, password);
Use these headers in your API request
fetch('https://api.example.com/resource', { headers })
.then((response) => {
// Handle the API response
})
.catch((error) => {
console.error(error);
});
Authorizes an HTTP request by adding authorization headers.
Kind: global function
Returns: RequestInit
- The updated request configuration with authorization headers.
Param | Type | Description |
---|---|---|
requestConfig | RequestInit |
The configuration for the HTTP request. |
authToken | string |
The authorization token (e.g., bearer token). |
Example
Authorize an API request with a bearer token
const apiUrl = 'https://api.example.com/resource';
const authToken = 'Bearer myAuthToken';
const requestConfig = {
method: 'GET',
};
const authorizedConfig = authorizeRequest(requestConfig, authToken);
fetch(apiUrl, authorizedConfig)
.then((response) => {
// Handle the API response
})
.catch((error) => {
console.error(error);
});
Logs information about an API call.
Kind: global function
Param | Type | Description |
---|---|---|
method | string |
The HTTP method of the API call (e.g., 'GET', 'POST'). |
url | string |
The URL of the API endpoint. |
headers | Headers |
The request headers. |
[requestBody] | string |
The request body, if applicable. |
[responseBody] | string |
The response body, if applicable. |
Example
Log an API call
const apiUrl = 'https://api.example.com/resource';
const requestHeaders = new Headers({
'Authorization': 'Bearer myAuthToken',
'Content-Type': 'application/json',
});
const requestBody = JSON.stringify({ key: 'value' });
Simulate an API call and log it
const response = await fetch(apiUrl, {
method: 'POST',
headers: requestHeaders,
body: requestBody,
});
const responseBody = await response.text();
logAPICall('POST', apiUrl, requestHeaders, requestBody, responseBody);
Monitors an API call by tracking start time, end time, and response status.
Kind: global function
Returns: Promise.<Response>
- A Promise that resolves with the API response.
Param | Type | Description |
---|---|---|
method | string |
The HTTP method of the API call (e.g., 'GET', 'POST'). |
url | string |
The URL of the API endpoint. |
apiCallPromise | Promise.<Response> |
The Promise representing the API call. |
Example
Monitor an API call
const apiUrl = 'https://api.example.com/resource';
Create a Promise representing the API call
const apiCallPromise = fetch(apiUrl, {
method: 'GET',
headers: {
'Authorization': 'Bearer myAuthToken',
},
});
Monitor the API call and log the response status
monitorAPICall('GET', apiUrl, apiCallPromise)
.then((response) => {
console.log('API call completed with status:', response.status);
})
.catch((error) => {
console.error('API call failed:', error);
});
Caches an API response using a cache key and stores it in memory.
Kind: global function
Param | Type | Description |
---|---|---|
cacheKey | string |
The key for caching the API response. |
response | Response |
The API response to cache. |
Retrieves a cached API response using a cache key.
Kind: global function
Returns: Response
| null
- The cached API response, or null if not found.
Param | Type | Description |
---|---|---|
cacheKey | string |
The key for retrieving the cached API response. |
Validates and sanitizes request parameters before making an API request.
Kind: global function
Returns: Object
- The sanitized request parameters.
Param | Type | Description |
---|---|---|
params | Object |
The request parameters object. |
Example
Validate and sanitize request parameters before making an API request
const requestParams = {
query: 'search term',
page: 1,
// Add more parameters as needed
};
const sanitizedParams = validateRequestParameters(requestParams);
Make an API request with the sanitized parameters
fetch('https://api.example.com/resource', {
method: 'GET',
// Pass sanitizedParams as query parameters or in the request body
})
.then((response) => {
// Handle the API response
})
.catch((error) => {
console.error('API request failed:', error);
});
Sets the "Content-Type" header for an HTTP request.
Kind: global function
Returns: Headers
- The updated headers object with the "Content-Type" header.
Param | Type | Description |
---|---|---|
headers | Headers |
The headers object for the request. |
contentType | string |
The content type to set (e.g., 'application/json'). |
Example
Create an HTTP request with a custom Content-Type header
const apiUrl = 'https://api.example.com/resource';
const requestData = {
key: 'value'
};
const headers = new Headers();
setRequestContentType(headers, 'application/json');
fetch(apiUrl, {
method: 'POST',
headers,
body: JSON.stringify(requestData),
})
.then((response) => {
// Handle the API response
})
.catch((error) => {
console.error('API request failed:', error);
});
Maps API data to a model or object.
Kind: global function
Returns: Object
- The mapped model or object.
Param | Type | Description |
---|---|---|
apiData | Object |
The data received from the API response. |
Example
Map API data to a user model
const apiResponse = {
id: 1,
username: 'john_doe',
email: 'john@example.com',
// Add more properties as needed
};
const userModel = mapAPIDataToModel(apiResponse);
Now you can work with the user model in your application
console.log('User ID:', userModel.id);
console.log('Username:', userModel.username);
console.log('Email:', userModel.email);
Connects to a WebSocket server.
Kind: global function
Returns: WebSocket
- The WebSocket instance representing the connection.
Param | Type | Description |
---|---|---|
url | string |
The URL of the WebSocket server. |
Example
Connect to a WebSocket server
const socketUrl = 'wss://api.example.com/socket';
const socket = connectWebSocket(socketUrl);
Set up event handlers for the WebSocket
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
// You can send messages or perform other actions here
};
socket.onmessage = (event) => {
console.log('WebSocket message received:', event.data);
// Handle incoming WebSocket messages
};
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
// Handle WebSocket closure
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
// Handle WebSocket errors
};
Sends a message over a WebSocket connection.
Kind: global function
Param | Type | Description |
---|---|---|
socket | WebSocket |
The WebSocket instance representing the connection. |
message |
string | Blob | ArrayBuffer
|
The message to send. |
Example
Send a text message over a WebSocket connection
const socketUrl = 'wss://api.example.com/socket';
const socket = connectWebSocket(socketUrl);
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
// Send a text message
sendWebSocketMessage(socket, 'Hello, WebSocket!');
};
socket.onmessage = (event) => {
console.log('WebSocket message received:', event.data);
// Handle incoming WebSocket messages
};
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
// Handle WebSocket closure
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
// Handle WebSocket errors
};
Closes a WebSocket connection gracefully.
Kind: global function
Param | Type | Default | Description |
---|---|---|---|
socket | WebSocket |
The WebSocket instance to close. | |
[code] | number |
1000 |
A numeric status code indicating the reason for closure. |
[reason] | string |
A human-readable explanation for the closure. |
Example
Close a WebSocket connection gracefully
const socketUrl = 'wss://api.example.com/socket';
const socket = new WebSocket(socketUrl);
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
// Perform some operations, then close the connection
closeWebSocketConnection(socket, 1000, 'Connection closed gracefully');
};
socket.onmessage = (event) => {
console.log('WebSocket message received:', event.data);
// Handle incoming WebSocket messages
};
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
// Handle WebSocket closure
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
// Handle WebSocket errors
};
Sanitizes input data to remove potentially harmful characters or validate against specific criteria.
Kind: global function
Returns: string
- The sanitized input data.
Param | Type | Description |
---|---|---|
input | string |
The input data to sanitize. |
Example
Sanitize user-provided input
const userInput = '<script>alert("Hello, World!");</script>';
const sanitizedInput = sanitizeInput(userInput);
Use the sanitized input in your application
console.log('Sanitized input:', sanitizedInput);
Uploads a file to a remote API endpoint.
Kind: global function
Returns: Promise.<Response>
- A Promise that resolves with the API response.
Param | Type | Description |
---|---|---|
apiUrl | string |
The URL of the API endpoint to upload the file to. |
file | File |
The File object representing the file to upload. |
Example
Upload a file to the API
const apiUrl = 'https://api.example.com/upload';
const fileInput = document.getElementById('fileInput'); // Assuming an HTML file input element.
const file = fileInput.files[0]; // Get the selected file from the input element.
if (file) {
uploadFileToAPI(apiUrl, file)
.then((response) => {
// Handle the API response after successful upload
console.log('File uploaded successfully:', response);
})
.catch((error) => {
// Handle errors during file upload
console.error('File upload failed:', error);
});
} else {
console.error('No file selected for upload.');
}
Initiates the download of a file from a remote API endpoint.
Kind: global function
Param | Type | Description |
---|---|---|
apiUrl | string |
The URL of the API endpoint to download the file from. |
fileName | string |
The desired name for the downloaded file. |
Example
Initiate the download of a file from the API
const apiUrl = 'https://api.example.com/download';
const fileName = 'example-file.txt'; // Specify the desired file name.
downloadFileFromAPI(apiUrl, fileName);
Retrieves a list of nearby locations or points of interest based on a geographical coordinate.
Kind: global function
Returns: Promise.<Array.<Object>>
- A Promise that resolves with an array of nearby locations.
Param | Type | Description |
---|---|---|
latitude | number |
The latitude of the reference location. |
longitude | number |
The longitude of the reference location. |
radius | number |
The search radius in meters from the reference location. |
category | string |
The category or type of locations to search for (e.g., 'restaurant', 'gas station'). |
Calculates the distance between two sets of geographical coordinates using the Haversine formula.
Kind: global function
Returns: number
- The distance in meters.
Param | Type | Description |
---|---|---|
lat1 | number |
Latitude of the first location. |
lon1 | number |
Longitude of the first location. |
lat2 | number |
Latitude of the second location. |
lon2 | number |
Longitude of the second location. |
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.
Param | Type | Description |
---|---|---|
apiKey | string |
The API key to be added to the headers. |
[headers] | Object |
Additional HTTP headers to include in the request. |
Example
Authorize an API request with an API key
const apiKey = 'your_api_key';
const apiUrl = 'https://api.example.com/resource';
const headers = authorizeWithApiKey(apiKey);
Include the updated headers in your API request
const requestOptions = {
method: 'GET',
headers: {
...headers,
// Add any additional headers if needed
},
};
fetch(apiUrl, requestOptions)
.then((response) => {
// Handle the API response
})
.catch((error) => {
// Handle API request errors
});
Refreshes an OAuth access token using a refresh token.
Kind: global function
Returns: Promise.<string>
- A Promise that resolves with the new access token.
Param | Type | Description |
---|---|---|
refreshToken | string |
The OAuth refresh token. |
clientId | string |
The OAuth client ID. |
clientSecret | string |
The OAuth client secret. |
tokenEndpoint | string |
The OAuth token endpoint URL. |
Example
Refresh an access token using a refresh token
const refreshToken = 'your_refresh_token';
const clientId = 'your_client_id';
const clientSecret = 'your_client_secret';
const tokenEndpoint = 'https://oauth.example.com/token';
refreshAccessToken(refreshToken, clientId, clientSecret, tokenEndpoint)
.then((accessToken) => {
// Use the refreshed access token for API requests
console.log('Refreshed access token:', accessToken);
})
.catch((error) => {
// Handle errors during token refresh
console.error('Error refreshing access token:', error);
});
Apply exponential backoff for retrying a network request with a maximum number of retries.
Kind: global function
Returns: Promise.<any>
- A Promise that resolves with the result of the successful request or rejects after exhausting retries.
Param | Type | Description |
---|---|---|
requestFn | function |
A function that performs the network request and returns a Promise. |
maxRetries | number |
The maximum number of retry attempts. |
baseDelay | number |
The base delay in milliseconds before the first retry. |
Example
Example usage with a fetch request:
const apiUrl = 'https://api.example.com/resource';
function performRequest() {
return fetch(apiUrl)
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
});
}
applyExponentialBackoff(performRequest, 3, 1000)
.then((result) => {
// Handle the successful response
console.log('Success:', result);
})
.catch((error) => {
// Handle the error after retries
console.error('Error:', error);
});
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.
Param | Type | Description |
---|---|---|
rateLimitHeader | string |
The value of the 'X-RateLimit-Reset' HTTP header from the API response. |
Example
Example usage with a response containing rate limit information:
const responseHeaders = {
'X-RateLimit-Limit': '5000',
'X-RateLimit-Remaining': '4998',
'X-RateLimit-Reset': '1632796800', // Unix timestamp for the reset time
};
const resetTimestamp = checkRateLimitExpiry(responseHeaders['X-RateLimit-Reset']);
console.log('Rate limit will reset at:', new Date(resetTimestamp * 1000));
Logs an error message to the console or a logging service.
Kind: global function
Param | Type | Default | Description |
---|---|---|---|
error |
string | Error
|
The error message or Error object to be logged. | |
[level] | string |
""error"" |
The log level (e.g., "error", "warn", "info", "debug"). |
Example
Example usage to log an error message
const errorMessage = 'An error occurred while processing the request';
logError(errorMessage);
Example usage to log an Error object
try {
// Code that may throw an error
throw new Error('This is a custom error');
} catch (error) {
logError(error);
}
Monitors the performance of an API call by measuring the execution time and logging it.
Kind: global function
Returns: Promise.<any>
- A Promise that resolves with the API response.
Param | Type | Description |
---|---|---|
apiEndpoint | string |
The URL or endpoint of the API being called. |
apiCall | function |
A function that makes the API call and returns a Promise. |
Example
Example usage to monitor the performance of an API call
const apiUrl = 'https://api.example.com/resource';
async function fetchDataFromAPI() {
// Perform the API call
const response = await fetch(apiUrl);
// Monitor the API call performance
await monitorAPICallPerformance(apiUrl, async () => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
});
}
fetchDataFromAPI()
.then((result) => {
// Handle the successful API response
console.log('API Data:', result);
})
.catch((error) => {
// Handle API request errors
console.error('Error fetching data from API:', error);
});
Invalidates a cache entry by removing it from the cache.
Kind: global function
Param | Type | Description |
---|---|---|
cacheKey | string |
The key or identifier of the cache entry to be invalidated. |
Example
Example usage to invalidate a cache entry
const cacheKey = 'apiData:resource123';
Invalidate the cache entry
invalidateCache(cacheKey);
Clears the entire cache by removing all entries.
Kind: global function
Example
Example usage to clear the entire cache
clearCache();
Validates an API response against an expected schema.
Kind: global function
Throws:
-
Error
Throws an error if the response does not match the expected schema.
Param | Type | Description |
---|---|---|
apiResponse | object |
The API response object to be validated. |
expectedSchema | object |
The expected schema object. |
Example
Example usage to validate an API response
const apiResponse = {
id: 1,
name: 'John Doe',
email: 'johndoe@example.com',
};
const expectedSchema = {
id: Number,
name: String,
email: String,
};
try {
validateResponseSchema(apiResponse, expectedSchema);
console.log('API response is valid.');
} catch (error) {
console.error('API response validation failed:', error.message);
}
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).
Param | Type | Description |
---|---|---|
contentTypeHeader | string |
The 'Content-Type' header value from an HTTP response. |
Example
Example usage to parse a 'Content-Type' header
const contentTypeHeader = 'application/json; charset=utf-8';
const parsedContentType = parseContentTypeHeader(contentTypeHeader);
console.log('Media Type:', parsedContentType.mediaType); // 'application/json'
console.log('Charset:', parsedContentType.charset); // 'utf-8'
Transforms data for export to a CSV file format.
Kind: global function
Returns: string
- A CSV-formatted string representing the transformed data.
Param | Type | Description |
---|---|---|
data | Array.<object> |
The data to be transformed for export. |
Example
Example usage to transform data for export to CSV
const data = [
{ name: 'John', age: 30, city: 'New York' },
{ name: 'Alice', age: 25, city: 'Los Angeles' },
{ name: 'Bob', age: 35, city: 'Chicago' },
];
const csvData = transformDataForExport(data);
console.log(csvData);
Subscribes to a WebSocket topic or channel.
Kind: global function
Param | Type | Description |
---|---|---|
socket | WebSocket |
The WebSocket connection to subscribe with. |
topic | string |
The name or identifier of the topic or channel to subscribe to. |
callback | function |
A callback function to handle messages received on the subscribed topic. |
Example
Example usage to subscribe to a WebSocket topic
const socket = new WebSocket('wss://example.com/socket');
function handleTopicMessage(message) {
console.log('Received message on topic:', message);
// Add your custom logic to handle messages for the subscribed topic
}
subscribeToWebSocketTopic(socket, 'my-topic', handleTopicMessage);
Encrypts data using the AES-GCM encryption algorithm.
Kind: global function
Returns: string
- The encrypted data in hexadecimal format.
Param | Type | Description |
---|---|---|
data | string |
The data to be encrypted. |
encryptionKey | string |
The encryption key (must be 32 bytes for AES-256-GCM). |
iv | string |
The initialization vector (IV), typically 12 bytes for AES-GCM. |
Example
Example usage to encrypt data
const dataToEncrypt = 'Sensitive information';
const encryptionKey = 'your-32-byte-secret-key';
const iv = 'your-12-byte-iv';
const encryptedData = encryptData(dataToEncrypt, encryptionKey, iv);
console.log('Encrypted Data:', encryptedData);
Deletes a file on an API using an HTTP DELETE request.
Kind: global function
Returns: Promise.<void>
- A promise that resolves when the file is successfully deleted.
Param | Type | Description |
---|---|---|
apiUrl | string |
The URL of the API endpoint that handles file deletion. |
fileId | string |
The identifier or filename of the file to be deleted. |
authToken | string |
An optional authentication token, if required by the API. |
Example
Example usage to delete a file on an API
const apiUrl = 'https://api.example.com/files';
const fileId = 'file123';
const authToken = 'your-authentication-token'; // Optional
deleteFileOnAPI(apiUrl, fileId, authToken)
.then(() => {
console.log('File deleted successfully.');
})
.catch((error) => {
console.error('File deletion failed:', error.message);
});
Downloads a file from a URL and returns it as a Base64-encoded string.
Kind: global function
Returns: Promise.<string>
- A promise that resolves with the Base64-encoded string of the downloaded file.
Param | Type | Description |
---|---|---|
fileUrl | string |
The URL of the file to be downloaded. |
Example
Example usage to download a file as Base64
const fileUrl = 'https://example.com/path/to/file.pdf';
downloadFileAsBase64(fileUrl)
.then((base64String) => {
console.log('File downloaded as Base64:', base64String);
})
.catch((error) => {
console.error('File download failed:', error.message);
});
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.
Param | Type | Description |
---|---|---|
lat1 | number |
Latitude of the first location in degrees. |
lon1 | number |
Longitude of the first location in degrees. |
lat2 | number |
Latitude of the second location in degrees. |
lon2 | number |
Longitude of the second location in degrees. |
Example
Example usage to calculate the distance between two locations
const lat1 = 40.7128; // Latitude of New York City
const lon1 = -74.0060; // Longitude of New York City
const lat2 = 34.0522; // Latitude of Los Angeles
const lon2 = -118.2437; // Longitude of Los Angeles
const distance = getDistanceBetweenLocations(lat1, lon1, lat2, lon2);
console.log('Distance:', distance.toFixed(2), 'km');
Retrieves the element at the specified index.
Kind: global function
Returns: any
- The element at the specified index.
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to retrieve the element from. |
index | number |
The index of the element to retrieve. |
Example
const myArray = [1, 2, 3, 4, 5];
const element = get(myArray, 2); // Retrieves the element at index 2 (value: 3)
console.log(element); // Output: 3
Sets the element at the specified index to a new value.
Kind: global function
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to modify. |
index | number |
The index of the element to set. |
value | any |
The new value to set at the specified index. |
Example
const myArray = [1, 2, 3, 4, 5];
set(myArray, 2, 6); // Sets the element at index 2 to 6
console.log(myArray); // Output: [1, 2, 6, 4, 5]
Returns the number of elements in the array.
Kind: global function
Returns: number
- The number of elements in the array.
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to get the length of. |
Example
const myArray = [1, 2, 3, 4, 5];
const arrayLength = length(myArray); // Retrieves the length of the array (value: 5)
console.log(arrayLength); // Output: 5
Appends an element to the end of the array.
Kind: global function
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to push the element into. |
element | any |
The element to append to the end of the array. |
Example
const myArray = [1, 2, 3];
push(myArray, 4); // Appends the element 4 to the end of the array
console.log(myArray); // Output: [1, 2, 3, 4]
Removes and returns the last element of the array.
Kind: global function
Returns: any
- The last element removed from the array.
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to pop the last element from. |
Example
const myArray = [1, 2, 3];
const poppedElement = pop(myArray); // Removes and returns the last element (value: 3)
console.log(poppedElement); // Output: 3
console.log(myArray); // Output: [1, 2]
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.
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to search for the target element. |
target | any |
The element to search for. |
Example
const myArray = [1, 2, 3, 4, 5];
const index = find(myArray, 3); // Finds the index of the element 3 (value: 2)
console.log(index); // Output: 2
Checks if the array contains a specific element.
Kind: global function
Returns: boolean
- true
if the array contains the target element, false
otherwise.
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to check for the target element. |
target | any |
The element to check for. |
Example
const myArray = [1, 2, 3, 4, 5];
const containsElement = contains(myArray, 3); // Checks if the element 3 is in the array (value: true)
console.log(containsElement); // Output: true
Creates a shallow copy of the array.
Kind: global function
Returns: Array.<any>
- A shallow copy of the input array.
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to copy. |
Example
const originalArray = [1, 2, 3];
const copiedArray = copy(originalArray); // Creates a shallow copy of the array
console.log(copiedArray); // Output: [1, 2, 3]
Removes all elements from the array.
Kind: global function
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to clear. |
Example
const myArray = [1, 2, 3, 4, 5];
clear(myArray); // Removes all elements from the array
console.log(myArray); // Output: []
Reverses the order of elements in the array.
Kind: global function
Param | Type | Description |
---|---|---|
arr | Array.<any> |
The array to reverse. |
Example
const myArray = [1, 2, 3, 4, 5];
reverse(myArray); // Reverses the order of elements in the array
console.log(myArray); // Output: [5, 4, 3, 2, 1]
Promisifies a function such that the function returns a promise.
To know more about promisification, check https://javascript.info/promisify.
To learn about how promises work check https://www.freecodecamp.org/news/guide-to-javascript-promises/#why-should-you-care-about-promises
Kind: global function
Returns: A function which returns a promise which enclosed the function sent as argument.
Param | Description |
---|---|
fn | The function to be promisified |
Promisifies multiple functions.
To know more about promisification, check https://javascript.info/promisify.
To learn about how promises work check https://www.freecodecamp.org/news/guide-to-javascript-promises/#why-should-you-care-about-promises
Kind: global function
Returns: Type Object | null - An object containing function names as keys and promisified version of the respected function as its value.
Param | Description |
---|---|
functions | Type Array - An array of functions to be promisified |
Creates a timeout for a promise.
To use with multiple promises, just send a promise from Promise.all to it.
To learn about how promises work check https://www.freecodecamp.org/news/guide-to-javascript-promises/#why-should-you-care-about-promises
Kind: global function
Default: 30
Returns: Type Promise - A promise which resolves when the promise sent as parameter is resolved. Rejects when promise sent in parameter is rejected or timeout function is executed.
Param | Description |
---|---|
promise | Type Promise - Th promise to be timed out. |
timeout | Type Number - Number of seconds for timeout. Default value is 30. |
Retries executing a function until it is resolved or until number of tries reaches the specified amount.
To learn about how promises work check https://www.freecodecamp.org/news/guide-to-javascript-promises/#why-should-you-care-about-promises
Kind: global function
Default: 3
Returns: - Type Promise - the result of the function, whether it is resolved or rejected.
Param | Default | Description |
---|---|---|
fn | Type Function - The function to be executed | |
tries | 3 |
Type number - Number of times the function should retry running. Default value is 3. |
...args | Type any - parameters of the function. |
Fetch data from a remote server using the specified URL.
This function makes an HTTP GET request to the provided URL and returns the response data as a JavaScript object.
Kind: global function
Returns: Promise.<any>
- A Promise that resolves to the fetched data.
Throws:
-
Error
If the HTTP request fails or the response status is not OK.
Param | Type | Description |
---|---|---|
url | string |
The URL to fetch data from. |
[options] | Object |
Optional options for the fetch request. |
Example
Fetch data from a JSON API
const apiUrl = 'https://api.example.com/data';
try {
const data = await fetchData(apiUrl);
console.log('Fetched data:', data);
} catch (error) {
console.error('Error fetching data:', error.message);
}
Example
Fetch data with custom headers
const apiUrl = 'https://api.example.com/secure-data';
const headers = {
Authorization: 'Bearer your-access-token',
'Content-Type': 'application/json',
};
const options = {
method: 'GET',
headers,
};
try {
const data = await fetchData(apiUrl, options);
console.log('Fetched data with custom headers:', data);
} catch (error) {
console.error('Error fetching data with custom headers:', error.message);
}
Fetch data from a remote server using the specified URL and return a Promise.
This function makes an HTTP GET request to the provided URL and returns a Promise that resolves to the fetched data.
Kind: global function
Returns: Promise.<any>
- A Promise that resolves to the fetched data.
Throws:
-
Error
If the HTTP request fails or the response status is not OK.
Param | Type | Description |
---|---|---|
url | string |
The URL to fetch data from. |
Example
Fetch data from a JSON API
const apiUrl = 'https://api.example.com/data';
fetchDataPromise(apiUrl)
.then((data) => {
console.log('Fetched data:', data);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
Download a file from a remote server and save it to the local file system.
This function makes an HTTP GET request to the provided URL, downloads the file, and saves it to the specified local file path.
Kind: global function
Returns: Promise.<void>
- A Promise that resolves when the file is successfully downloaded and saved.
Throws:
-
Error
If the download or file-saving process fails.
Param | Type | Description |
---|---|---|
url | string |
The URL of the file to download. |
localFilePath | string |
The local file path where the downloaded file will be saved. |
Example
Download a file and save it locally
const fileUrl = 'https://example.com/files/sample.txt';
const localPath = './downloads/sample.txt';
try {
await downloadFile(fileUrl, localPath);
console.log('File downloaded and saved successfully.');
} catch (error) {
console.error('Error downloading or saving the file:', error.message);
}
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.
Param | Type | Description |
---|---|---|
inputFunction | function |
The function to debounce. |
delay | number |
The delay in milliseconds to wait before executing the debounced function. |
Example
Define a function to handle user input (e.g., search)
function handleUserInput(query) {
// Perform some action with the query
console.log('Query:', query);
}
Debounce the input function with a 300ms delay const debouncedInputFunction = debounceInput(handleUserInput, 300);
Simulate user input events debouncedInputFunction('A'); // This will not immediately trigger handleUserInput. debouncedInputFunction('Ap'); // This will also not immediately trigger handleUserInput. After a 300ms pause in input, handleUserInput('Apple') will be called once. debouncedInputFunction('Apple');
<a name="debounceSearch"></a>
## debounceSearch(searchFunction, delay) ⇒ <code>function</code>
Debounce a search function to reduce the frequency of search requests.
This function takes a search function and returns a debounced version of it. When
the debounced function is called, it will delay executing the original search
function until a specified delay has passed without any additional calls. This can
be useful for scenarios like handling user search input to reduce the frequency of
search requests to a server.
**Kind**: global function
**Returns**: <code>function</code> - A debounced version of the search function.
| Param | Type | Description |
| --- | --- | --- |
| searchFunction | <code>function</code> | The search function to debounce. |
| delay | <code>number</code> | The delay in milliseconds to wait before executing the debounced search. |
**Example**
```js
Define a function to perform a search
async function performSearch(query) {
// Perform a search and retrieve search results
console.log('Searching for:', query);
// Simulate an asynchronous search request
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log('Search results for:', query);
}
Debounce the search function with a 300ms delay
const debouncedSearch = debounceSearch(performSearch, 300);
Simulate user input events triggering the search
debouncedSearch('apple'); // This will not immediately trigger performSearch.
debouncedSearch('apples'); // This will also not immediately trigger performSearch.
After a 300ms pause in input, performSearch('applesauce') will be called once.
debouncedSearch('applesauce');
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.
Param | Type | Description |
---|---|---|
asyncFunction | function |
The asynchronous function to memoize. |
Example
Define an asynchronous function to be memoized
async function fetchDataFromServer(userId) {
// Simulate an asynchronous data fetching operation
await new Promise((resolve) => setTimeout(resolve, 1000));
return `Data for user ${userId}`;
}
Memoize the async function
const memoizedFetchData = memoizeAsyncFunction(fetchDataFromServer);
Use the memoized function with different arguments
memoizedFetchData('123')
.then((data) => {
console.log(data); // Output: "Data for user 123"
});
The result for the same argument is cached, so it's retrieved instantly
memoizedFetchData('123')
.then((data) => {
console.log(data); // Output: "Data for user 123"
});
A different argument triggers a new asynchronous call
memoizedFetchData('456')
.then((data) => {
console.log(data); // Output: "Data for user 456"
});
Generate asynchronous values using an async generator function.
This function creates an asynchronous generator function that yields values one by
one using the yield
keyword. It allows you to produce asynchronous values in a
controlled and sequential manner.
Kind: global function
Returns: AsyncGenerator.<number, void, undefined>
- An async generator that yields numbers.
Param | Type | Description |
---|---|---|
count | number |
The number of values to generate. |
interval | number |
The interval in milliseconds between each value. |
Example
Create an async generator that yields numbers from 1 to 5 with a 500ms interval
const generator = asyncGenerator(5, 500);
Iterate over the values using for-await-of
(async () => {
for await (const value of generator) {
console.log('Received value:', value);
}
})();
Output:
Received value: 1 (after 500ms)
Received value: 2 (after 500ms)
Received value: 3 (after 500ms)
Received value: 4 (after 500ms)
Received value: 5 (after 500ms)
Consume values from an async generator and process them using a callback function.
This function takes an async generator and a callback function. It iterates over
the values produced by the generator using for-await-of
and processes each value
by passing it to the provided callback function.
Kind: global function
Returns: Promise.<void>
- A Promise that resolves when all values have been consumed and processed.
Param | Type | Description |
---|---|---|
asyncGenerator | AsyncGenerator.<any, void, undefined> |
The async generator to consume values from. |
callback | function |
The callback function to process each value. |
Example
Create an async generator that yields numbers from 1 to 3 with a 500ms interval
const generator = asyncGenerator(3, 500);
Define a callback function to process each value
function processValue(value) {
console.log('Received value:', value);
}
Consume values from the generator using the callback
consumeAsyncGenerator(generator, processValue)
.then(() => {
console.log('All values consumed.');
});
Output:
Received value: 1 (after 500ms)
Received value: 2 (after 500ms)
Received value: 3 (after 500ms)
All values consumed.
Asynchronously iterate over an array and apply a function to each element.
This function takes an array and an asynchronous callback function. It iterates over each element in the array and applies the asynchronous callback function to each element in sequence, awaiting the completion of each operation before proceeding to the next.
Kind: global function
Returns: Promise.<void>
- A Promise that resolves when all elements have been processed.
Param | Type | Description |
---|---|---|
array | Array.<any> |
The array to iterate over. |
callback | function |
The asynchronous callback function to apply to each element. |
Example
Define an array of items to process
const items = [1, 2, 3, 4, 5];
Define an asynchronous callback function to process each item
async function processItem(item) {
// Simulate an asynchronous operation
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log('Processed item:', item);
}
Use asyncForEach to process each item in the array
asyncForEach(items, processItem)
.then(() => {
console.log('All items processed.');
});
Output:
Processed item: 1 (after 1000ms)
Processed item: 2 (after 1000ms)
Processed item: 3 (after 1000ms)
Processed item: 4 (after 1000ms)
Processed item: 5 (after 1000ms)
All items processed.
Asynchronously map an array of values to a new array of transformed values.
This function takes an array and an asynchronous mapping function. It maps each element in the array to a new value by applying the asynchronous mapping function and collects the results in a new array. The resulting array contains the transformed values in the same order as the original array.
Kind: global function
Returns: Promise.<Array.<any>>
- A Promise that resolves to the array of transformed values.
Param | Type | Description |
---|---|---|
array | Array.<any> |
The array of values to map. |
mapper | function |
The asynchronous mapping function that transforms each value. |
Example
Define an array of numbers to transform
const numbers = [1, 2, 3, 4, 5];
Define an asynchronous mapping function that doubles each number
async function doubleNumber(number) {
// Simulate an asynchronous operation
await new Promise((resolve) => setTimeout(resolve, 1000));
return number * 2;
}
Use asyncMap to transform the array of numbers
asyncMap(numbers, doubleNumber)
.then((doubledNumbers) => {
console.log('Doubled numbers:', doubledNumbers);
});
Output:
Doubled numbers: [2, 4, 6, 8, 10] (after 1000ms)
Cancel an ongoing asynchronous task.
This function takes an ongoing asynchronous task represented as a Promise and attempts to cancel it. It returns a Promise that resolves when the task is successfully canceled or rejects if the task cannot be canceled.
Kind: global function
Returns: Promise.<void>
- A Promise that resolves when the task is canceled.
Param | Type | Description |
---|---|---|
asyncTask | Promise.<void> |
The ongoing asynchronous task to cancel. |
Example
Define an asynchronous task that takes time to complete
async function performAsyncTask() {
await new Promise((resolve) => setTimeout(resolve, 5000));
console.log('Async task complete.');
}
Start the asynchronous task
const taskPromise = performAsyncTask();
After 2 seconds, attempt to cancel the task
setTimeout(async () => {
try {
await cancelAsyncTask(taskPromise);
console.log('Task canceled successfully.');
} catch (error) {
console.error('Failed to cancel task:', error.message);
}
}, 2000);
Output (after 2 seconds):
Task canceled successfully.
(After 5 seconds): Async task complete.
Profile the execution time of an asynchronous function.
This function takes an asynchronous function and profiles its execution time. It measures the time it takes for the function to complete and returns a Promise that resolves with the execution time in milliseconds.
Kind: global function
Returns: Promise.<number>
- A Promise that resolves with the execution time in milliseconds.
Param | Type | Description |
---|---|---|
asyncFunction | function |
The asynchronous function to profile. |
Example
Define an asynchronous function to profile
async function performAsyncTask() {
// Simulate an asynchronous operation
await new Promise((resolve) => setTimeout(resolve, 2000));
}
Profile the asynchronous function
profileAsyncFunction(performAsyncTask)
.then((executionTime) => {
console.log(`Async task took ${executionTime}ms to complete.`);
});
Output: Async task took 2000ms to complete.
Monitor resource usage of an asynchronous task.
This function takes an asynchronous task function and monitors its resource usage, such as CPU and memory. It returns a Promise that resolves when the task is complete and provides information about the resource usage.
Kind: global function
Returns: Promise.<Object>
- A Promise that resolves with resource usage information.
Param | Type | Description |
---|---|---|
asyncTask | function |
The asynchronous task to monitor. |
Example
Define an asynchronous task that consumes CPU and memory
async function heavyAsyncTask() {
const array = [];
for (let i = 0; i < 1000000; i++) {
array.push(i);
}
console.log('Async task complete.');
}
Monitor the resource usage of the asynchronous task
monitorResourceUsageAsync(heavyAsyncTask)
.then((resourceUsage) => {
console.log('Resource usage:', resourceUsage);
});
Output:
Async task complete.
Resource usage: { cpuUsage: 12.34, memoryUsage: 567890 }
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.
Param | Type | Description |
---|---|---|
path | string |
The path to the JSON file to read. |
Example
Read a JSON file and retrieve its data
const data = readJson('/path/to/file.json');
console.log(data);
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.
Param | Type | Description |
---|---|---|
path | string |
The path to the JSON file to write. |
data | any |
The JavaScript data to be written to the JSON file. |
Example
Write JavaScript data to a JSON file and retrieve its data
const data = { name: 'John', age: 30 };
const result = writeJson('/path/to/file.json', data);
console.log(result);
Converts an array of JSON objects into a CSV (Comma-Separated Values) string.
Kind: global function
Returns: string
- - A CSV string representing the data.
Param | Type | Description |
---|---|---|
data | any |
An array of JSON objects to be converted to CSV. |
Example
Convert an array of JSON objects to a CSV string
const data = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
...
];
const csvString = json2Csv(data);
console.log(csvString);
Removes missing values (null or undefined) from a 2D array.
Kind: global function
Returns: Array.<Array.<any>>
- - The cleaned data without missing values.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data containing missing values. |
Example
const dataWithMissingValues = [
[1, 2, null],
[4, undefined, 6],
[7, 8, 9],
];
const cleanedData = removeMissingValues(dataWithMissingValues);
Result: [[7, 8, 9]]
Scales numeric features in a 2D array to the [0, 1] range using Min-Max scaling.
Kind: global function
Returns: Array.<Array.<number>>
- - The scaled data.
Param | Type | Description |
---|---|---|
data | Array.<Array.<number>> |
The input data with numeric features to be scaled. |
Example
const numericData = [
[2, 4, 8],
[1, 3, 9],
[5, 7, 10],
];
const scaledData = scaleNumericFeatures(numericData);
Result: [[0.25, 0.25, 0.0], [0.0, 0.0, 1.0], [1.0, 1.0, 1.0]]
One-hot encodes categorical variables in a 2D array.
Kind: global function
Returns: Array.<Array.<number>>
- - The one-hot encoded data.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data containing categorical variables. |
categoricalColumns | Array.<number> |
An array of column indices containing categorical variables. |
Example
const dataWithCategorical = [
["Red", 10],
["Blue", 5],
["Green", 8],
];
const categoricalColumns = [0];
const oneHotEncodedData = oneHotEncode(dataWithCategorical, categoricalColumns);
Result: [[1, 0, 0, 10], [0, 1, 0, 5], [0, 0, 1, 8]]
Normalizes numeric data using Z-Score normalization (mean = 0, std. deviation = 1).
Kind: global function
Returns: Array.<Array.<number>>
- - The normalized data.
Param | Type | Description |
---|---|---|
data | Array.<Array.<number>> |
The input data with numeric features to be normalized. |
Example
const numericData = [
[10, 20, 30],
[15, 25, 35],
[20, 30, 40],
];
const normalizedData = zScoreNormalizeData(numericData);
Result: [[-1.224744871391589, -1.224744871391589, -1.224744871391589],
[0, 0, 0],
[1.224744871391589, 1.224744871391589, 1.224744871391589]]
Splits data into training and testing sets based on a given split ratio.
Kind: global function
Returns: Array.<Array.<Array.<any>>>
- - An array containing training and testing sets.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data to be split. |
splitRatio | number |
The ratio of data to be used for training (e.g., 0.8 for 80% training). |
Example
const inputData = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const splitRatio = 0.8;
const [trainingData, testingData] = splitData(inputData, splitRatio);
Result: trainingData contains 80% of the data, and testingData contains 20% of the data.
Shuffles the rows of a 2D array randomly.
Kind: global function
Returns: Array.<Array.<any>>
- - The shuffled data.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data to be shuffled. |
Example
const inputData = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const shuffledData = shuffleData(inputData);
Result: A random permutation of the input data rows.
Data Resampling (e.g., for imbalanced datasets).
Kind: global function
Returns: Array.<Array.<any>>
- - The resampled data with balanced classes.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data with a target column (binary classification). |
targetColumn | number |
The index of the target column (0-based). |
resampleCount | number |
The number of samples to create in the minority class. |
Example
const inputData = [
[1, 0],
[2, 0],
[3, 0],
[4, 1],
[5, 1],
];
const targetColumn = 1;
const resampleCount = 3;
const resampledData = resampleData(inputData, targetColumn, resampleCount);
Result: Additional samples added to the minority class (class 1).
Feature Selection.
Kind: global function
Returns: Array.<Array.<any>>
- - The data with selected features.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data with features. |
selectedColumns | Array.<number> |
An array of column indices to select as features. |
Example
const inputData = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const selectedColumns = [0, 2];
const selectedData = selectFeatures(inputData, selectedColumns);
Result: Data with only the selected features (columns 0 and 2).
Data Transformation (e.g., log-transform for skewed data).
Kind: global function
Returns: Array.<Array.<number>>
- - The transformed data (e.g., log-transformed).
Param | Type | Description |
---|---|---|
data | Array.<Array.<number>> |
The input data with numeric features to be transformed. |
Example
const numericData = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const logTransformedData = logTransform(numericData);
Result: Log-transformed data.
Splits data into multiple subsets for cross-validation.
Kind: global function
Returns: Array.<Array.<Array.<T>>>
- - An array of data splits for cross-validation.
Param | Type | Description |
---|---|---|
data | Array.<Array.<T>> |
The input data to be split. |
folds | number |
The number of cross-validation folds. |
Example
const inputData = [
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10],
];
const folds = 3;
const dataSplits = crossValidationSplit(inputData, folds);
Result: Array of data splits for 3-fold cross-validation.
Imputes missing values (null or undefined) in a 2D array with a specified imputation value.
Kind: global function
Returns: Array.<Array.<any>>
- - The data with missing values imputed using the specified value.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data containing missing values. |
imputationValue | any |
The value to use for imputing missing values. |
Example
const dataWithMissingValues = [
[1, 2, null],
[4, undefined, 6],
[7, 8, 9],
];
const imputedData = imputeMissingValues(dataWithMissingValues, 0);
Result: Missing values are replaced with 0.
Creates polynomial features for a dataset.
Kind: global function
Returns: Array.<Array.<number>>
- - The data with polynomial features.
Param | Type | Description |
---|---|---|
data | Array.<Array.<number>> |
The input data with numeric features. |
degree | number |
The maximum degree of polynomial features to create. |
Example
const inputData = [
[1, 2],
[3, 4],
[5, 6],
];
const degree = 2;
const polynomialData = createPolynomialFeatures(inputData, degree);
Result: Original features and polynomial features up to degree 2.
Discretizes (bins) numeric data into a specified number of bins.
Kind: global function
Returns: Array.<Array.<number>>
- - The binned data.
Param | Type | Description |
---|---|---|
data | Array.<Array.<number>> |
The input data with numeric features. |
numBins | number |
The number of bins to discretize the data into. |
Example
const numericData = [
[1.2, 3.5],
[2.5, 4.8],
[4.0, 6.1],
];
const numBins = 3;
const binnedData = binNumericData(numericData, numBins);
Result: Discretized data into 3 bins.
Encodes ordinal categorical columns in a dataset using a custom encoding map.
Kind: global function
Returns: Array.<Array.<any>>
- - The data with ordinal categorical columns encoded.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data containing ordinal categorical columns. |
ordinalColumns | Array.<number> |
An array of column indices containing ordinal categorical columns. |
encodingMap | Object |
A mapping of category labels to numerical values. |
Example
const dataWithOrdinal = [
['Low', 'A'],
['High', 'B'],
['Medium', 'C'],
['Low', 'A'],
];
const ordinalColumns = [0];
const encodingMap = { 'Low': 1, 'Medium': 2, 'High': 3 };
const encodedData = encodeOrdinal(dataWithOrdinal, ordinalColumns, encodingMap);
Result: Ordinal categorical column 'Low' is encoded as 1, 'Medium' as 2, 'High' as 3.
Scales numeric features in a 2D array to the [0, 1] range using Min-Max scaling.
Kind: global function
Returns: Array.<Array.<number>>
- - The scaled data.
Param | Type | Description |
---|---|---|
data | Array.<Array.<number>> |
The input data with numeric features to be scaled. |
Example
const numericData = [
[2, 4, 8],
[1, 3, 9],
[5, 7, 10],
];
const scaledData = minMaxScaling(numericData);
Result: Features scaled to the [0, 1] range.
Tokenizes an array of text data into words.
Kind: global function
Returns: Array.<Array.<string>>
- - The tokenized data where each entry is an array of words.
Param | Type | Description |
---|---|---|
textData | Array.<string> |
The input text data to be tokenized. |
Example
const textData = [
'This is a sample sentence.',
'Tokenization is important.',
'NLP tasks require tokenization.',
];
const tokenizedData = textTokenization(textData);
Result: Tokenized sentences into words.
Removes common stop words from an array of tokenized text data.
Kind: global function
Returns: Array.<Array.<string>>
- - The text data with stop words removed.
Param | Type | Description |
---|---|---|
textData | Array.<Array.<string>> |
The input tokenized text data. |
Example
const tokenizedData = [
['this', 'is', 'a', 'sample', 'sentence'],
['tokenization', 'is', 'important'],
['nlp', 'tasks', 'require', 'tokenization'],
];
const dataWithoutStopWords = removeStopWords(tokenizedData);
Result: Text data with stop words removed.
Stems words in an array of tokenized text data.
Kind: global function
Returns: Array.<Array.<string>>
- - The text data with words stemmed.
Param | Type | Description |
---|---|---|
textData | Array.<Array.<string>> |
The input tokenized text data. |
Example
const tokenizedData = [
['running', 'jumps', 'played'],
['happiness', 'joyful', 'happily'],
['flies', 'flying', 'flew'],
];
const stemmedData = stemWords(tokenizedData);
Result: Text data with words stemmed.
Parses date and time strings in specified columns of a 2D array and converts them into Date objects.
Kind: global function
Returns: Array.<Array.<Date>>
- - The data with date and time strings converted to Date objects.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data containing date and time strings. |
dateTimeColumns | Array.<number> |
An array of column indices containing date and time strings. |
Example
const dataWithDateTime = [
['2023-09-26', '08:30:00'],
['2023-09-27', '14:45:00'],
['2023-09-28', '10:15:00'],
];
const dateTimeColumns = [0, 1];
const parsedData = parseDateTime(dataWithDateTime, dateTimeColumns);
Result: Date and time strings converted to Date objects.
Extracts time-related features from an array of Date objects.
Kind: global function
Returns: Array.<Array.<any>>
- - The data with extracted time-related features.
Param | Type | Description |
---|---|---|
data | Array.<Array.<Date>> |
The input data containing Date objects. |
Example
const dateData = [
[new Date('2023-09-26T08:30:00'), new Date('2023-09-27T14:45:00')],
[new Date('2023-09-28T10:15:00'), new Date('2023-09-29T16:30:00')],
];
const timeFeatures = extractTimeFeatures(dateData);
Result: Extracted time-related features.
Removes outliers from a 2D array of numeric data based on a specified threshold.
Kind: global function
Returns: Array.<Array.<number>>
- - The data with outliers removed.
Param | Type | Description |
---|---|---|
data | Array.<Array.<number>> |
The input data with numeric features. |
threshold | number |
The threshold for outlier detection (e.g., Z-score threshold). |
Example
const numericData = [
[2, 4, 8],
[1, 3, 9],
[5, 7, 10],
];
const threshold = 2.0; // Adjust the threshold as needed
const dataWithoutOutliers = removeOutliers(numericData, threshold);
Result: Data with outliers removed based on the threshold.
Encodes nominal categorical columns in a dataset using one-hot encoding.
Kind: global function
Returns: Array.<Array.<any>>
- - The data with nominal categorical columns encoded using one-hot encoding.
Param | Type | Description |
---|---|---|
data | Array.<Array.<any>> |
The input data containing nominal categorical columns. |
nominalColumns | Array.<number> |
An array of column indices containing nominal categorical columns. |
Example
const dataWithNominal = [
['Red', 'A'],
['Blue', 'B'],
['Green', 'A'],
['Red', 'C'],
];
const nominalColumns = [0, 1];
const encodedData = encodeNominal(dataWithNominal, nominalColumns);
Result: Nominal categorical columns encoded using one-hot encoding.
Standardizes numeric features in a 2D array by subtracting the mean and dividing by the standard deviation.
Kind: global function
Returns: Array.<Array.<number>>
- - The standardized data.
Param | Type | Description |
---|---|---|
data | Array.<Array.<number>> |
The input data with numeric features to be standardized. |
Example
const numericData = [
[2, 4, 8],
[1, 3, 9],
[5, 7, 10],
];
const standardizedData = standardizeData(numericData);
Result: Standardized features.
Augments an array of image data by applying specified transformations, such as rotation and flipping.
Kind: global function
Returns: Array.<MyImageData>
- An array of augmented image data.
Throws:
-
Error
If the canvas context is not available.
Param | Type | Description |
---|---|---|
images | Array.<MyImageData> |
An array of image data to be augmented. |
augmentationOptions | AugmentationOptions |
Options for augmenting the images. |
Example
Define an array of image data
const imageArray = /* MyImageData array * /;
Define augmentation options
const options = {
rotate: 90, // Rotate images by 90 degrees (clockwise)
flipHorizontal: true, // Flip images horizontally
flipVertical: false // Do not flip images vertically
};
Augment the image data
const augmentedImages = augmentImageData(imageArray, options);
console.log(augmentedImages); // Output: An array of augmented image data.
Loads data from a CSV file and returns it as an array of Data objects.
Kind: global function
Returns: Promise.<Array.<Data>>
- A Promise that resolves with an array of Data objects.
Throws:
-
Error
If there is an error reading or parsing the CSV file.
Param | Type | Description |
---|---|---|
filename | string |
The path to the CSV file to load. |
Example
Example usage:
loadCSV('data.csv')
.then((data) => {
// Process the loaded data
console.log(data);
})
.catch((error) => {
console.error('Error loading CSV:', error);
});
Filters an array of Data objects based on a custom condition.
Kind: global function
Returns: Array.<Data>
- An array of Data objects that meet the filter condition.
Param | Type | Description |
---|---|---|
data | Array.<Data> |
The array of Data objects to filter. |
filterFn | function |
The filtering function that returns true to include an item. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 35 },
];
const filteredData = filterData(data, (item) => item.age > 30);
console.log(filteredData); // Output: [{ id: 3, name: 'Charlie', age: 35 }]
Maps an array of Data objects to a new array using a custom mapping function.
Kind: global function
Returns: Array.<Data>
- An array of Data objects resulting from applying the mapping function.
Param | Type | Description |
---|---|---|
data | Array.<Data> |
The array of Data objects to map. |
mapFn | function |
The mapping function that transforms each item. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 35 },
];
const mappedData = mapData(data, (item) => ({ ...item, age: item.age + 1 }));
console.log(mappedData);
Output:
[
{ id: 1, name: 'Alice', age: 31 },
{ id: 2, name: 'Bob', age: 26 },
{ id: 3, name: 'Charlie', age: 36 },
]
Sorts an array of Data objects based on a specified key in ascending or descending order.
Kind: global function
Returns: Array.<Data>
- A new array of Data objects sorted based on the specified key.
Param | Type | Default | Description |
---|---|---|---|
data | Array.<Data> |
The array of Data objects to sort. | |
key | string |
The key by which to sort the objects. | |
[ascending] | boolean |
true |
Whether to sort in ascending order (default) or descending order. |
Example
Example usage:
const data = [
{ id: 3, name: 'Charlie', age: 35 },
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
];
const sortedDataAsc = sortData(data, 'age');
console.log(sortedDataAsc);
Output: [{ id: 2, name: 'Bob', age: 25 }, { id: 1, name: 'Alice', age: 30 }, { id: 3, name: 'Charlie', age: 35 }]
const sortedDataDesc = sortData(data, 'name', false);
console.log(sortedDataDesc);
Output: [{ id: 3, name: 'Charlie', age: 35 }, { id: 1, name: 'Alice', age: 30 }, { id: 2, name: 'Bob', age: 25 }]
Groups an array of Data objects by a specified key and returns a Map of grouped Data arrays.
Kind: global function
Returns: Map.<string, Array.<Data>>
- A Map where keys are unique values of the specified key and values are arrays of grouped Data objects.
Param | Type | Description |
---|---|---|
data | Array.<Data> |
The array of Data objects to group. |
key | string |
The key by which to group the objects. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 30 },
];
const groupedData = groupBy(data, 'age');
console.log(groupedData.get('25'));
Output: [{ id: 2, name: 'Bob', age: 25 }]
console.log(groupedData.get('30'));
Output: [{ id: 1, name: 'Alice', age: 30 }, { id: 3, name: 'Charlie', age: 30 }]
Aggregates and summarizes data from an array of Data objects based on a specified grouping key and aggregation function.
Kind: global function
Returns: Map.<string, any>
- A Map where keys are unique values of the specified group key, and values are the results of aggregation for each group.
Param | Type | Description |
---|---|---|
data | Array.<Data> |
The array of Data objects to aggregate. |
groupKey | string |
The key by which to group the data. |
aggregationFn | function |
The aggregation function that summarizes grouped data. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 30 },
];
Aggregation function to calculate the average age in each group
const averageAgeAggregation (groupedData) => {
const totalAge = groupedData.reduce((sum, item) => sum + item.age, 0);
return totalAge / groupedData.length;
};
const aggregatedData = aggregate(data, 'age', averageAgeAggregation);
console.log(aggregatedData.get('25'));
Output: 25
console.log(aggregatedData.get('30'));
Output: 30
Exports an array of data to a CSV file.
Kind: global function
Param | Type | Description |
---|---|---|
data | Array.<Data> |
An array of data to export. |
filename | string |
The name of the CSV file. |
Example
Example usage:
const data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 35 },
];
exportCSV(data, 'exported_data.csv');
Normalizes an array of numeric data using min-max scaling.
Kind: global function
Returns: Array.<number>
- The normalized data.
Param | Type | Description |
---|---|---|
data | Array.<number> |
An array of numeric data to normalize. |
Example
Example usage:
const data = [10, 20, 30, 40, 50];
const normalizedData = minMaxNormalizeData(data);
console.log(normalizedData);
Output: [0, 0.25, 0.5, 0.75, 1]
Counts the number of words in a text string.
Kind: global function
Returns: number
- The number of words in the text.
Param | Type | Description |
---|---|---|
text | string |
The input text. |
Example
Example usage:
const text = "This is an example sentence.";
const wordCount = countWords(text);
console.log(wordCount);
Output: 5
Finds and returns an array of keywords present in a text string.
Kind: global function
Returns: Array.<string>
- An array of keywords found in the text.
Param | Type | Description |
---|---|---|
text | string |
The input text. |
keywords | Array.<string> |
An array of keywords to search for. |
Example
Example usage:
const text = "This is a sample text containing keywords like JavaScript and TypeScript.";
const keywords = ["JavaScript", "TypeScript", "sample"];
const foundKeywords = findKeywords(text, keywords);
console.log(foundKeywords);
Output: ["JavaScript", "TypeScript", "sample"]
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.
Param | Type | Description |
---|---|---|
date | Date |
The date object to format. |
pattern | string |
The format pattern. Use 'YYYY' for year, 'MM' for month, 'DD' for day, 'hh' for hours, 'mm' for minutes, 'ss' for seconds, and 'SSS' for milliseconds. |
Example
Create a Date object representing September 26, 2023, 14:30:15
const date = new Date(2023, 8, 26, 14, 30, 15);
Format the date using a custom pattern
const formattedDate = format_date(date, 'YYYY-MM-DD hh:mm:ss.SSS');
console.log('Formatted date:', formattedDate);
Output: Formatted date: 2023-09-26 14:30:15.000
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
Param | Type | Description |
---|---|---|
sizeInBytes | number |
The size in bytes to convert to human-readable format. |
Example
Convert a size in bytes to human-readable format
const sizeInBytes = 123456789; // 123,456,789 bytes
const humanReadableSize = to_human_readable(sizeInBytes);
console.log('Human-readable size:', humanReadableSize);
Output: Human-readable size: 117.74 MB
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.
Param | Type | Description |
---|---|---|
dateString | string |
The date string to parse. |
format | string |
The format of the date string using placeholders. |
Example
Parse a date string in 'YYYY-MM-DD' format
const dateString = '2023-09-26';
const format = 'YYYY-MM-DD';
const parsedDate = parse_date(dateString, format);
if (parsedDate !== null) {
console.log('Parsed date:', parsedDate.toLocaleDateString());
} else {
console.error('Invalid date format.');
}
Output: Parsed date: 9/26/2023 (the actual format may vary depending on locale)
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.
Param | Type | Description |
---|---|---|
iso8601String | string |
The ISO 8601 date string to parse. |
Example
Parse an ISO 8601 date string
const iso8601String = '2023-09-26T14:30:15Z';
const parsedDate = parse_iso8601(iso8601String);
if (parsedDate !== null) {
console.log('Parsed date:', parsedDate.toLocaleString());
} else {
console.error('Invalid ISO 8601 date format.');
}
Output: Parsed date: 9/26/2023, 2:30:15 PM (the actual format may vary depending on locale)
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 thandate2
, it returns a negative value. - If
date1
is later thandate2
, 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.
Param | Type | Description |
---|---|---|
date1 | Date |
The first Date object to compare. |
date2 | Date |
The second Date object to compare. |
Example
Compare two Date objects
const date1 = new Date(2023, 8, 26);
const date2 = new Date(2023, 8, 27);
const result = compare_dates(date1, date2);
if (result < 0) {
console.log('date1 is earlier than date2.');
} else if (result > 0) {
console.log('date1 is later than date2.');
} else {
console.log('date1 and date2 are equal.');
}
Output: date1 is earlier than date2.
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 returnsfalse
. - Time zone differences should be taken into account when comparing dates across different time zones.
Param | Type | Description |
---|---|---|
date | Date |
The Date object to check. |
Example
Check if a Date object represents a past date
const pastDate = new Date(2020, 0, 1); // January 1, 2020
const isPast = is_past(pastDate);
if (isPast) {
console.log('The date is in the past.');
} else {
console.log('The date is in the present or future.');
}
Output: The date is in the past.
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 returnsfalse
. - Time zone differences should be taken into account when comparing dates across different time zones.
Param | Type | Description |
---|---|---|
date | Date |
The Date object to check. |
Example
Check if a Date object represents a future date
const futureDate = new Date(2030, 0, 1); // January 1, 2030
const isFuture = is_future(futureDate);
if (isFuture) {
console.log('The date is in the future.');
} else {
console.log('The date is in the present or past.');
}
Output: The date is in the future.
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.
Param | Type | Description |
---|---|---|
date | Date |
The Date object to which days will be added. |
daysToAdd | number |
The number of days to add. Positive values add days to the future, and negative values subtract days from the past. |
Example
Add 7 days to a Date object
const currentDate = new Date(); // Current date and time
const futureDate = add_days(currentDate, 7);
console.log('Current date:', currentDate.toLocaleDateString());
console.log('Future date:', futureDate.toLocaleDateString());
Output example:
Current date: 9/26/2023 (the actual format may vary depending on locale)
Future date: 10/3/2023 (the actual format may vary depending on locale)
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.
Param | Type | Description |
---|---|---|
date | Date |
The Date object from which days will be subtracted. |
daysToSubtract | number |
The number of days to subtract. Positive values subtract days from the past, and negative values add days to the future. |
Example
Subtract 7 days from a Date object
const currentDate = new Date(); // Current date and time
const pastDate = subtract_days(currentDate, 7);
console.log('Current date:', currentDate.toLocaleDateString());
console.log('Past date:', pastDate.toLocaleDateString());
Output example:
Current date: 9/26/2023 (the actual format may vary depending on locale)
Past date: 9/19/2023 (the actual format may vary depending on locale)
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 thanstartDate
. - A negative value indicates that
endDate
is earlier thanstartDate
. - 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.
Param | Type | Description |
---|---|---|
startDate | Date |
The starting Date object. |
endDate | Date |
The ending Date object. |
Example
Calculate the number of days between two dates
const date1 = new Date(2023, 8, 26); // September 26, 2023
const date2 = new Date(2023, 9, 3); // October 3, 2023
const daysBetween = days_between_dates(date1, date2);
console.log('Days between:', daysBetween);
Output: Days between: 7
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, andfalse
if it is not.
Param | Type | Description |
---|---|---|
date | Date |
The Date object to check. |
Example
Check if a Date object represents a valid date and time
const validDate = new Date(2023, 1, 28); // February 28, 2023
const invalidDate = new Date(2023, 1, 29); // February 29, 2023 (not a leap year)
const isValid1 = is_valid_date(validDate);
const isValid2 = is_valid_date(invalidDate);
console.log('IsValid1:', isValid1); // Output: IsValid1: true
console.log('IsValid2:', isValid2); // Output: IsValid2: false
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, andfalse
otherwise.
Param | Type | Description |
---|---|---|
year | number |
The year to check for leap year status. |
Example
Check if a year is a leap year
const leapYear = 2024;
const nonLeapYear = 2023;
const isLeap1 = is_leap_year(leapYear);
const isLeap2 = is_leap_year(nonLeapYear);
console.log('IsLeap1:', isLeap1); // Output: IsLeap1: true
console.log('IsLeap2:', isLeap2); // Output: IsLeap2: false
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
andendDate
if they are within the specified range.
Param | Type | Default | Description |
---|---|---|---|
startDate | Date |
The start date of the range (inclusive). | |
endDate | Date |
The end date of the range (inclusive). | |
[step] | number |
1 |
Optional step interval in days (default is 1 day). |
Example
Generate an array of dates within a range
const start = new Date(2023, 8, 1); // September 1, 2023
const end = new Date(2023, 8, 5); // September 5, 2023
const dateRange = generate_date_range(start, end);
dateRange.forEach(date => {
console.log(date.toLocaleDateString());
});
Output example:
9/1/2023
9/2/2023
9/3/2023
9/4/2023
9/5/2023
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
andendDate
are included in the generated array if they fall within the specified range.
Param | Type | Description |
---|---|---|
startDate | Date |
The start date of the range (inclusive). |
endDate | Date |
The end date of the range (inclusive). |
Example
Generate an array of months within a range
const start = new Date(2023, 0, 15); // January 15, 2023
const end = new Date(2023, 3, 10); // April 10, 2023
const monthRange = generate_month_range(start, end);
monthRange.forEach(month => {
console.log(month.toLocaleDateString(undefined, { year: 'numeric', month: 'long' }));
});
Output example:
January 2023
February 2023
March 2023
April 2023
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.
Param | Type | Description |
---|---|---|
date | Date |
The Date object to convert to a Unix timestamp. |
Example
Convert a Date object to a Unix timestamp
const someDate = new Date(2023, 8, 26, 12, 0, 0); // September 26, 2023, 12:00:00 PM
const timestamp = date_to_unix_timestamp(someDate);
console.log('Unix timestamp:', timestamp);
Output example:
Unix timestamp: 1691059200
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.
Param | Type | Description |
---|---|---|
timestamp | number |
The Unix timestamp to convert to a Date object. |
Example
Convert a Unix timestamp to a Date object
const unixTimestamp = 1691059200; // September 26, 2023, 12:00:00 PM
const date = unix_timestamp_to_date(unixTimestamp);
console.log('Date:', date.toLocaleString());
Output example:
Date: 9/26/2023, 12:00:00 PM (the actual format may vary depending on locale)
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").
Param | Type | Description |
---|---|---|
date | Date |
The Date object for which to get the day of the week. |
Example
Get the day of the week for a Date object
const someDate = new Date(2023, 8, 26); // September 26, 2023
const dayOfWeek = get_day_of_week(someDate);
console.log('Day of the week:', dayOfWeek);
Output example:
Day of the week: Tuesday
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 andfalse
if it is a weekday.
Param | Type | Description |
---|---|---|
date | Date |
The Date object to check. |
Example
Check if a Date object falls on a weekend
const weekendDate = new Date(2023, 8, 30); // September 30, 2023 (Saturday)
const weekdayDate = new Date(2023, 8, 26); // September 26, 2023 (Tuesday)
const isWeekend1 = is_weekend(weekendDate);
const isWeekend2 = is_weekend(weekdayDate);
console.log('IsWeekend1:', isWeekend1); // Output: IsWeekend1: true
console.log('IsWeekend2:', isWeekend2); // Output: IsWeekend2: false
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.
Param | Type | Description |
---|---|---|
date | Date |
The Date object to which business days will be added. |
daysToAdd | number |
The number of business days to add. |
Example
Add 5 business days to a Date object
const startDate = new Date(2023, 8, 26); // September 26, 2023 (Monday)
const endDate = add_business_days(startDate, 5);
console.log('Start date:', startDate.toLocaleDateString());
console.log('End date:', endDate.toLocaleDateString());
Output example:
Start date: 9/26/2023
End date: 10/3/2023
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.
Param | Type | Description |
---|---|---|
date | Date |
The Date object for which to find the next business day. |
Example
Get the next business day after a Date object
const someDate = new Date(2023, 8, 28); // September 28, 2023 (Wednesday)
const nextBusinessDay = next_business_day(someDate);
console.log('Next business day:', nextBusinessDay.toLocaleDateString());
Output example:
Next business day: 9/29/2023
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").
Param | Type | Description |
---|---|---|
date | Date |
The Date object to convert. |
targetTimeZone | string |
The target time zone in IANA Time Zone format (e.g., "America/New_York"). |
Example
Convert a Date object to a different time zone
const someDate = new Date(2023, 0, 15, 12, 0, 0); // January 15, 2023, 12:00:00 PM
const newYorkTimeZone = "America/New_York";
const newYorkDate = convert_timezone(someDate, newYorkTimeZone);
console.log('Original Date:', someDate.toLocaleString());
console.log('New York Date:', newYorkDate.toLocaleString());
Output example:
Original Date: 1/15/2023, 12:00:00 PM (the actual format may vary depending on locale)
New York Date: 1/15/2023, 7:00:00 AM (the actual format may vary depending on locale)
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).
Param | Type | Description |
---|---|---|
birthdate | Date |
The Date object representing the birthdate. |
referenceDate | Date |
The reference Date object for age calculation (e.g., current date). |
Example
Calculate the age based on birthdate and reference date
const birthdate = new Date(1990, 8, 15); // September 15, 1990
const currentDate = new Date(); // Current date
const age = calculate_age(birthdate, currentDate);
console.log('Age:', age); // Output: Age: (calculated age based on current date)
Generates a random date within a specified date range.
Kind: global function
Returns: Date
- A random date within the specified range.
Param | Type | Description |
---|---|---|
startDate | Date |
The start date of the date range. |
endDate | Date |
The end date of the date range. |
Example
Generate a random date within a specific year (2023).
const startDate = new Date('2023-01-01');
const endDate = new Date('2023-12-31');
const randomDate = randomDate(startDate, endDate);
console.log(randomDate.toDateString()); // Output: A random date within the specified range.
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.
Param | Type | Description |
---|---|---|
startDate | Date |
The start date of the date range. |
endDate | Date |
The end date of the date range. |
weightedDays | Record.<number, number> |
An object mapping days of the week (0 for Sunday, 1 for Monday, etc.) to their respective weights. |
Example
Generate a random date within a week, with higher weights for weekend days.
const startDate = new Date('2023-09-26');
const endDate = new Date('2023-10-02');
const weightedDays = { 0: 1, 1: 2, 2: 2, 3: 1, 4: 1, 5: 3, 6: 3 }; // Higher weights for Saturday and Sunday
const randomDate = weightedRandomDate(startDate, endDate, weightedDays);
console.log(randomDate.toDateString()); // Output: A random date within the specified range, with weights considered.
Shifts a given date by a specified number of days and returns the shifted date.
Kind: global function
Returns: Date
- The shifted date.
Param | Type | Description |
---|---|---|
date | Date |
The input date to shift. |
daysToShift | number |
The number of days to shift the date (positive or negative). |
Example
Shift a date 5 days into the future
const originalDate = new Date('2023-09-26');
const shiftedDate = shiftDate(originalDate, 5);
console.log(shiftedDate.toDateString()); // Output: "Sat Oct 01 2023"
Shift a date 2 days into the past
const anotherDate = new Date('2023-09-26');
const anotherShiftedDate = shiftDate(anotherDate, -2);
console.log(anotherShiftedDate.toDateString()); // Output: "Mon Sep 24 2023"
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.
Param | Type | Description |
---|---|---|
startDate | Date |
The start date. |
endDate | Date |
The end date. |
Example
const today = new Date();
const futureDate = new Date(today);
futureDate.setDate(today.getDate() + 7); // 7 days in the future
const differenceString = formatDateDifference(today, futureDate);
console.log(differenceString); // Output: "1 week from now"
const pastDate = new Date(today);
pastDate.setDate(today.getDate() - 3); // 3 days in the past
const anotherDifferenceString = formatDateDifference(pastDate, today);
console.log(anotherDifferenceString); // Output: "3 days ago"
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.
Param | Type | Description |
---|---|---|
date | Date |
The input date to adjust. |
timezoneOffset | number |
The desired timezone offset in minutes (positive or negative). |
Example
Adjust a date for a timezone offset of +120 minutes (2 hours ahead)
const originalDate = new Date('2023-09-26T12:00:00Z');
const adjustedDate = adjustForTimezoneOffset(originalDate, 120);
console.log(adjustedDate); // Output: 2023-09-26T14:00:00.000Z
Adjust a date for a timezone offset of -180 minutes (3 hours behind)
const anotherDate = new Date('2023-09-26T12:00:00Z');
const anotherAdjustedDate = adjustForTimezoneOffset(anotherDate, -180);
console.log(anotherAdjustedDate); // Output: 2023-09-26T09:00:00.000Z
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.
Param | Type | Default | Description |
---|---|---|---|
date | Date |
The Date object for which to get the week number. | |
[weekNumberingSystem] |
"iso" | "us"
|
"iso" |
The week numbering system to use (default is ISO 8601). |
Example
Get the ISO week number for a Date object
const someDate = new Date(2023, 5, 15); // June 15, 2023
const isoWeekNumber = get_week_number(someDate, "iso");
console.log('ISO Week Number:', isoWeekNumber); // Output: ISO Week Number: 24
Get the US week number for the same Date object
const usWeekNumber = get_week_number(someDate, "us");
console.log('US Week Number:', usWeekNumber); // Output: US Week Number: 25
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.
Param | Type | Description |
---|---|---|
serializedDate | string |
The serialized string representation of the date. |
format | string |
The format pattern used for deserialization (e.g., "YYYY-MM-DD"). |
Example
Deserialize a string into a Date object
const serializedDate = "2023-09-15"; // September 15, 2023
const deserializedDate = deserialize_date(serializedDate, "YYYY-MM-DD");
console.log('Deserialized date:', deserializedDate.toDateString()); // Output: Deserialized date: Wed Sep 15 2023
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.
Param | Type | Description |
---|---|---|
date | Date |
The Date object to serialize. |
format | string |
The format pattern for serializing the Date (e.g., "YYYY-MM-DD"). |
Example
Serialize a Date object into a custom format
const someDate = new Date(2023, 8, 15); // September 15, 2023
const formattedDate = serialize_date(someDate, "YYYY-MM-DD");
console.log('Formatted date:', formattedDate); // Output: Formatted date: 2023-09-15
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 andfalse
otherwise.
Param | Type | Description |
---|---|---|
date | Date |
The Date object to check. |
startDate | Date |
The start date of the date range (inclusive). |
endDate | Date |
The end date of the date range (inclusive). |
Example
Check if a Date object falls within a date range
const dateToCheck = new Date(2023, 8, 15); // September 15, 2023
const rangeStart = new Date(2023, 7, 1); // August 1, 2023
const rangeEnd = new Date(2023, 8, 30); // September 30, 2023
const isInRange = is_date_in_range(dateToCheck, rangeStart, rangeEnd);
console.log('Is in range:', isInRange); // Output: Is in range: true
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.
Param | Type | Description |
---|---|---|
date | Date |
The Date object for which to get the fiscal period. |
fiscalYearStartMonth | number |
The month (1 to 12) in which the fiscal year starts. |
Example
Get the fiscal period for a Date object
const someDate = new Date(2023, 3, 15); // April 15, 2023
const fiscalPeriod = get_fiscal_period(someDate, 4); // Assuming fiscal year starts in April (month 4)
console.log('Fiscal Period:', fiscalPeriod); // Output: Fiscal Period: 12
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.
Param | Type | Description |
---|---|---|
date | Date |
The Date object for which to get the quarter. |
Example
Get the quarter of the year for a Date object
const someDate = new Date(2023, 5, 15); // June 15, 2023
const quarter = get_quarter(someDate);
console.log('Quarter:', quarter); // Output: Quarter: 2
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.
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to read. |
Example
const fileContent = read_file_contents('example.txt');
console.log(fileContent);
Writes data to a file, either by overwriting the existing content or appending to it.
Kind: global function
Param | Type | Default | Description |
---|---|---|---|
filename | string |
The path to the file to write to. | |
data | string |
The data to write to the file. | |
append | boolean |
false |
Whether to append the data to the file (default: false). |
Example
write_to_file('example.txt', 'Hello, World!');
write_to_file('example.txt', ' Appended text.', true);
Copies the contents of one file to another.
Kind: global function
Param | Type | Description |
---|---|---|
source | string |
The path to the source file to copy from. |
destination | string |
The path to the destination file to copy to. |
Example
copy_file('source.txt', 'destination.txt');
Renames a file or moves it to a different directory.
Kind: global function
Param | Type | Description |
---|---|---|
source | string |
The current path of the file. |
destination | string |
The new path or directory of the file. |
Example
move_file('oldname.txt', 'newname.txt');
move_file('file.txt', 'directory/newfile.txt');
Checks if a file exists at a specified path.
Kind: global function
Returns: boolean
- true
if the file exists, false
otherwise.
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to check. |
Example
if (file_exists('example.txt')) {
console.log('File exists!');
}
Deletes a file from the file system.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to delete. |
Example
delete_file('oldfile.txt');
Determines the size of a file in bytes.
Kind: global function
Returns: number
- The size of the file in bytes.
Param | Type | Description |
---|---|---|
filename | string |
The path to the file. |
Example
const fileSize = get_file_size('document.pdf');
console.log(`File size: ${fileSize} bytes`);
Determines the type or format of a file (e.g., text, binary, JSON, XML).
Kind: global function
Returns: string
- The file type or format.
Param | Type | Description |
---|---|---|
filename | string |
The path to the file. |
Example
const fileType = get_file_type('data.json');
console.log(`File type: ${fileType}`);
Sets or modifies file permissions (e.g., read, write, execute) on a file.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the file. |
permissions | number |
The permissions to set. |
Example
set_file_permissions('file.txt', 0o755); // Give read, write, and execute permissions to owner, and read and execute to others.
Reads data from a CSV file and parses it into a structured format (e.g., a list of dictionaries).
Kind: global function
Returns: Promise.<Array.<any>>
- A Promise that resolves with an array of objects representing the CSV data.
Param | Type | Description |
---|---|---|
filename | string |
The path to the CSV file to read. |
Example
const csvData = await read_csv_file('data.csv');
console.log(csvData);
Reads data from a JSON file and parses it into a dictionary or an object.
Kind: global function
Returns: any
- The parsed JSON data.
Param | Type | Description |
---|---|---|
filename | string |
The path to the JSON file to read. |
Example
const jsonData = read_json_file('data.json');
console.log(jsonData);
Writes data from a dictionary or an object to a JSON file.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the JSON file to write. |
data | any |
The data to write to the JSON file. |
Example
const data = { name: 'Alice', age: 30 };
write_json_file('output.json', data);
Compresses a file into an archive (e.g., ZIP).
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to compress. |
archive_filename | string |
The path and filename for the compressed archive. |
Example
compress_file('file.txt', 'file.zip');
Decompresses an archived file.
Kind: global function
Param | Type | Description |
---|---|---|
archive_filename | string |
The path to the compressed archive file. |
destination | string |
The path to the destination directory. |
Example
decompress_file('file.zip', 'extracted/');
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.
Param | Type | Description |
---|---|---|
filename | string |
The path to the text file to read. |
encoding | crypto.Encoding |
The character encoding to use (e.g., 'utf-8'). |
Example
const fileContent = read_text_file('textfile.txt', 'utf-8');
console.log(fileContent);
Calculates hash values (e.g., MD5, SHA-256) for a file's content.
Kind: global function
Returns: string
- The calculated hash value.
Param | Type | Description |
---|---|---|
filename | string |
The path to the file for which to calculate the hash. |
hash_algorithm | string |
The hash algorithm to use (e.g., 'md5', 'sha256'). |
Example
const md5Hash = calculate_file_hash('file.txt', 'md5');
console.log(`MD5 Hash: ${md5Hash}`);
Compares two files to check if their contents are identical.
Kind: global function
Returns: boolean
- true
if the files have identical contents, false
otherwise.
Param | Type | Description |
---|---|---|
file1 | string |
The path to the first file for comparison. |
file2 | string |
The path to the second file for comparison. |
Example
if (compare_files('file1.txt', 'file2.txt')) {
console.log('Files have identical contents.');
} else {
console.log('Files are not identical.');
}
Searches for a specific string or pattern within a file.
Kind: global function
Returns: boolean
- true
if the pattern is found, false
otherwise.
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to search in. |
search_pattern |
string | RegExp
|
The string or regular expression to search for. |
Example
if (search_in_file('document.txt', 'keyword')) {
console.log('Pattern found in the file.');
} else {
console.log('Pattern not found.');
}
Creates backup copies of files in a specified directory.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to create a backup of. |
backup_directory | string |
The directory where backup copies will be stored. |
Example
backup_file('important.txt', 'backup/');
Changes the creation, modification, or access timestamps of a file.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to modify timestamps for. |
timestamp_type | string |
The type of timestamp to change ('atime', 'mtime', or 'ctime'). |
new_timestamp | Date |
The new timestamp to set. |
Example
const newDate = new Date('2023-01-01T00:00:00Z');
change_file_timestamp('file.txt', 'mtime', newDate);
Merges the contents of multiple files into a single file.
Kind: global function
Param | Type | Description |
---|---|---|
output_filename | string |
The path to the output file where merged content will be saved. |
input_files | Array.<string> |
An array of paths to the input files to be merged. |
Example
merge_files('merged.txt', ['file1.txt', 'file2.txt', 'file3.txt']);
Reads a file in smaller chunks to conserve memory.
Kind: global function
Returns: Array.<Buffer>
- An array of chunks.
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to read. |
chunk_size | number |
The size of each chunk in bytes. |
Example
const chunks = read_file_in_chunks('largefile.txt', 1024); // Read in 1 KB chunks
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.
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to check permissions for. |
permission_type | string |
The type of permission to check ('read', 'write', 'execute'). |
Example
if (check_file_permissions('file.txt', 'read')) {
console.log('File is readable.');
} else {
console.log('File is not readable.');
}
Archives files into a single compressed file format (e.g., zip, tar).
Kind: global function
Param | Type | Description |
---|---|---|
output_archive | string |
The path and filename for the output archive. |
input_files | Array.<string> |
An array of paths to the input files to be archived. |
Example
archive_files('my_archive.zip', ['file1.txt', 'file2.txt']);
Counts the number of lines in a text file.
Kind: global function
Returns: number
- The number of lines in the file.
Param | Type | Description |
---|---|---|
filename | string |
The path to the text file to count lines in. |
Example
const lineCount = count_lines_in_file('textfile.txt');
console.log(`Line count: ${lineCount}`);
Changes the owner of a file.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to change ownership for. |
new_owner | string |
The username or UID of the new owner. |
Example
change_file_owner('file.txt', 'newuser');
Copies permissions from one file to another.
Kind: global function
Param | Type | Description |
---|---|---|
source_file | string |
The path to the source file to copy permissions from. |
destination_file | string |
The path to the destination file to apply permissions to. |
Example
copy_permissions('source.txt', 'destination.txt');
Retrieves metadata about a file, such as creation date, modification date, and size.
Kind: global function
Returns: fs.Stats
- An object containing file metadata.
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to retrieve metadata for. |
Example
const metadata = get_file_metadata('file.txt');
console.log(metadata);
Encrypts a file using a specified encryption key.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to encrypt. |
encryption_key | string |
The encryption key. |
Example
encrypt_file('file.txt', 'mysecretkey');
Decrypts an encrypted file.
Kind: global function
Param | Type | Description |
---|---|---|
encrypted_filename | string |
The path to the encrypted file. |
decryption_key | string |
The decryption key. |
Example
decrypt_file('encrypted.txt', 'mysecretkey');
Modifies a specific line in a text file.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the text file. |
line_number | number |
The line number to modify (1-based index). |
new_content | string |
The new content to replace the line with. |
Example
modify_line_in_file('textfile.txt', 3, 'Updated line content');
Removes specific permissions from a file.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to remove permissions from. |
permissions | string |
The permissions to remove (e.g., 'read', 'write', 'execute'). |
Example
remove_file_permissions('file.txt', 'write');
Uploads a file to a remote server.
Kind: global function
Param | Type | Description |
---|---|---|
local_filename | string |
The path to the local file to upload. |
remote_destination | string |
The destination on the remote server where the file will be uploaded. |
Example
upload_file('localfile.txt', 'remote_server:/path/to/destination/');
Downloads a file from a remote server.
Kind: global function
Param | Type | Description |
---|---|---|
remote_filename | string |
The path to the file on the remote server to download. |
local_destination | string |
The local destination where the file will be saved. |
Example
download_file('remote_server:/path/to/remotefile.txt', 'localfile.txt');
Converts the encoding of a text file.
Kind: global function
Param | Type | Description |
---|---|---|
input_filename | string |
The path to the input file with the source encoding. |
output_filename | string |
The path to the output file with the target encoding. |
source_encoding | string |
The source encoding of the file (e.g., 'utf-8', 'utf-16'). |
target_encoding | string |
The target encoding to convert the file to (e.g., 'utf-8', 'utf-16'). |
Example
convert_file_encoding('file.txt', 'converted.txt', 'utf-8', 'utf-16');
Filters lines in a text file based on a custom filter function.
Kind: global function
Param | Type | Description |
---|---|---|
input_filename | string |
The path to the input text file. |
output_filename | string |
The path to the output text file with filtered lines. |
filter_function | function |
The custom filter function that determines which lines to keep. |
Example
Example filter function that keeps lines containing the word 'apple'
function filter_function(line) {
return line.includes('apple');
}
filter_file_lines('input.txt', 'output.txt', filter_function);
Checks if a file is owned by a specific user.
Kind: global function
Param | Type | Description |
---|---|---|
filename | string |
The path to the file to check ownership. |
user | string |
The user to check ownership against. |
Example
check_file_ownership('file.txt', 'john');
Rotates and manages a limited number of backup copies of a file.
Kind: global function
Param | Type | Description |
---|---|---|
backup_directory | string |
The directory where backup copies will be stored. |
max_backups | number |
The maximum number of backup copies to retain. |
Example
rotate_file_backups('/backup', 5);
Extracts the names of all function declarations, function expressions, and arrow functions from a TypeScript file and returns them as an array.
Kind: global function
Returns: Array.<string>
- An array containing the names of all functions found in the file.
Throws:
-
Error
Throws an error if there's an issue reading the file or parsing its content.
Param | Type | Description |
---|---|---|
filePath | string |
The path to the TypeScript file to be analyzed. |
Example
Example usage:
const filePath = 'yourTypeScriptFile.ts'; // Replace with your file path
const functionNames = getFunctionNamesInFile(filePath);
console.log('Function names in the file:', functionNames);
Distance between two points on a geo map coordinate sysytem in Kilometer
Kind: global function
Returns: (type: number) Distance between (lat1, lon1) point and (lat2, long2) point in Kilometers.
Param | Description |
---|---|
lat1 | (type: number) latitude1 |
lon1 | (type: number) longitude1 |
lat2 | (type: number) latitude2 |
lon2 | (type: number) longitude2 |
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}`);
}
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.
Param | Type | Description |
---|---|---|
lat1 | number |
Latitude of the first point in degrees. |
lon1 | number |
Longitude of the first point in degrees. |
lat2 | number |
Latitude of the second point in degrees. |
lon2 | number |
Longitude of the second point in degrees. |
Example
const distance = calculateDistance(40.7128, -74.0060, 34.0522, -118.2437);
console.log(`Distance: ${distance.toFixed(2)} meters`);
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°).
Param | Type | Description |
---|---|---|
lat1 | number |
Latitude of the first point in degrees. |
lon1 | number |
Longitude of the first point in degrees. |
lat2 | number |
Latitude of the second point in degrees. |
lon2 | number |
Longitude of the second point in degrees. |
Example
const bearing = calculateBearing(40.7128, -74.0060, 34.0522, -118.2437);
console.log(`Initial Bearing: ${bearing.toFixed(2)} degrees`);
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.
Param | Type | Description |
---|---|---|
lat | number |
Latitude to check (-90 to 90 degrees). |
lon | number |
Longitude to check (-180 to 180 degrees). |
Example
const isValid = areCoordinatesValid(40.7128, -74.0060);
console.log(`Coordinates are valid: ${isValid}`);
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.
Param | Type | Description |
---|---|---|
distanceInMeters | number |
Distance in meters to format. |
units |
'metric' | 'imperial'
|
Units to use ('metric' for kilometers, 'imperial' for miles). |
Example
const distanceInMeters = 1500;
const formattedDistance = formatDistance(distanceInMeters, 'metric');
console.log(`Distance: ${formattedDistance}`);
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.
Param | Type | Description |
---|---|---|
distanceInMeters | number |
Distance in meters to convert to pixels. |
scaleInMetersPerPixel | number |
Map's scale in meters per pixel. |
Example
const distanceInMeters = 1000;
const scaleInMetersPerPixel = 10; // 10 meters per pixel on the map
const distanceInPixels = metersToPixels(distanceInMeters, scaleInMetersPerPixel);
console.log(`Distance in pixels: ${distanceInPixels}`);
Kind: global function
Returns: args
Param |
---|
args |
Parses and returns info about the call stack at the given index. Copied Code from Src: https://gist.github.com/ManotLuijiu/8f0be2f0ac0a8f6dd5dc47e2db332600
Initiate a Logger
Kind: global function
Returns: logger object
Param | Description |
---|---|
fileUrl | URL of File for storage. |
Initiate a Logger
Kind: global function
Returns: logger object
Param | Type | Description |
---|---|---|
fileUrl | string |
URL of File for storage. |
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.
Param | Type | Description |
---|---|---|
num | number |
The number for which to calculate the absolute value. |
Example
Example 1:
const result1 = absolute(-5); Returns 5
Example 2:
const result2 = absolute(10); Returns 10 (unchanged since it's already positive)
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.
Param | Type | Description |
---|---|---|
num | number |
The number for which to calculate the square root. |
Example
Example 1:
const result1 = squareRoot(16); Returns 4
Example 2:
const result2 = squareRoot(9); Returns 3
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.
Param | Type | Description |
---|---|---|
num | number |
The number for which to calculate the cube root. |
Example
Example 1:
const result1 = cubeRoot(8); Returns 2
Example 2:
const result2 = cubeRoot(27); Returns 3
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.
Param | Type | Description |
---|---|---|
array | Array.<number> |
An array of numbers to be multiplied. |
Example
Example 1:
const result1: number = multiplyArray([2, 3, 4]); Returns 24
Example 2:
const result2: number = multiplyArray([]); Throws an error (empty array)
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.
Param | Type | Description |
---|---|---|
array | Array.<number> |
An array of numbers for which to calculate the geometric mean. |
Example
Example 1:
const result1: number = geometricMean([2, 4, 8]); Returns 4
Example 2:
const result2: number = geometricMean([]); Throws an error (empty array)
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.
Param | Type | Description |
---|---|---|
array | Array.<number> |
An array of numbers for which to calculate the median. |
Example
Example 1:
const result1: number = median([2, 4, 8]); Returns 4
Example 2:
const result2: number = median([]); Throws an error (empty array)
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.
Param | Type | Description |
---|---|---|
array | Array.<number> |
An array of numbers for which to find the mode. |
Example
Example 1:
const result1: number = mode([2, 2, 3, 4, 4, 4, 5]); Returns 4
Example 2:
const result2: number = mode([]); Throws an error (empty array)
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.
Param | Type | Description |
---|---|---|
array | Array.<number> |
An array of numbers for which to calculate the mean squared error. |
Example
Example 1:
const result1: number = meanSquareError([2, 4, 8]); Returns 6.666666666666667
Example 2:
const result2: number = meanSquareError([]); Throws an error (empty array)
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.
Param | Type | Description |
---|---|---|
array | Array.<number> |
An array of numbers for which to calculate the variance. |
Example
Example 1:
const result1: number = variance([2, 4, 8]); Returns 6.666666666666667
Example 2:
const result2: number = variance([]); Throws an error (empty array)
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.
Param | Type | Description |
---|---|---|
array | Array.<number> |
An array of numbers for which to calculate the standard deviation. |
Example
Example 1:
const result1: number = standardDeviation([2, 4, 8]); Returns approximately 2.160246899469287
Example 2:
const result2: number = standardDeviation([]); Throws an error (empty array)
Calculates the rank and value of a given percentile in an array of numbers.
Kind: global function
Returns: Array.<number>
- An array containing the rank and value corresponding to the percentile.
Throws:
-
Error
Throws an error if the input is not a valid array of numbers or if the percentile is out of range.
Remarks: The percentile rank is calculated as the rank (position) of the value that corresponds to the given percentile. It throws an error if the input is not a valid array of numbers or if the percentile is out of range.
Param | Type | Description |
---|---|---|
array | Array.<number> |
An array of numbers for which to calculate the percentile rank. |
percentile | number |
The percentile (0 to 100) for which to calculate the rank and value. |
Example
Example 1:
const result1: [number, number] = percentileRank([1, 2, 3, 4, 5], 50); Returns [3, 3]
Example 2:
const result2: [number, number] = percentileRank([], 75); Throws an error (empty array)
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.
Param | Type | Description |
---|---|---|
array | Array.<number> |
An array of numbers for which to calculate the percentile rank. |
key | number |
The value for which to calculate the percentile rank. |
Example
Example 1:
const result1: number = percentile([1, 2, 3, 4, 5], 3); Returns 60
Example 2:
const result2: number = percentile([], 75); Throws an error (empty array)
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.
Param | Type | Description |
---|---|---|
num | number |
The number to which to add the percentage. |
percentage | number |
The percentage to add to the number. |
Example
Example 1:
const result1: number = addPercentage(100, 10); Returns 110
Example 2:
const result2: number = addPercentage(50, -20); Returns 40
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.
Param | Type | Description |
---|---|---|
radians | number |
The angle in radians for which to calculate the sine. |
Example
Example 1:
const result1: number = sin(Math.PI / 2); Returns 1 (sine of 90 degrees)
Example 2:
const result2: number = sin(0); Returns 0 (sine of 0 degrees)
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.
Param | Type | Description |
---|---|---|
radians | number |
The angle in radians for which to calculate the cosine. |
Example
Example 1:
const result1: number = cos(Math.PI / 3); Returns 0.5 (cosine of 60 degrees)
Example 2:
const result2: number = cos(0); Returns 1 (cosine of 0 degrees)
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.
Param | Type | Description |
---|---|---|
radians | number |
The angle in radians for which to calculate the tangent. |
Example
Example 1:
const result1: number = tan(Math.PI / 4); Returns 1 (tangent of 45 degrees)
Example 2:
const result2: number = tan(0); Returns 0 (tangent of 0 degrees)
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.
Param | Type | Description |
---|---|---|
radians | number |
The angle in radians for which to calculate the cosecant. |
Example
Example 1:
const result1: number = cosec(Math.PI / 6); Returns 2 (cosecant of 30 degrees)
Example 2:
const result2: number = cosec(Math.PI / 2); Returns 1 (cosecant of 90 degrees)
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.
Param | Type | Description |
---|---|---|
radians | number |
The angle in radians for which to calculate the secant. |
Example
Example 1:
const result1: number = sec(Math.PI / 4); Returns approximately 1.4142135623730951 (secant of 45 degrees)
Example 2:
const result2: number = sec(Math.PI / 6); Returns 2 (secant of 30 degrees)
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.
Param | Type | Description |
---|---|---|
radians | number |
The angle in radians for which to calculate the cotangent. |
Example
Example 1:
const result1: number = cot(Math.PI / 4); Returns 1 (cotangent of 45 degrees)
Example 2:
const result2: number = cot(Math.PI / 6); Returns approximately 1.7320508075688772 (cotangent of 30 degrees)
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.
Param | Type | Description |
---|---|---|
num | number |
The number for which to calculate the arcsine in radians. |
Example
Example 1:
const result1: number = asin(0.5); Returns approximately 0.5235987755982989 (arcsine of 0.5)
Example 2:
const result2: number = asin(1); Returns approximately 1.5707963267948966 (arcsine of 1)
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.
Param | Type | Description |
---|---|---|
num | number |
The number for which to calculate the arccosine in radians. |
Example
Example 1:
const result1: number = acos(0.5); Returns approximately 1.0471975511965979 (arccosine of 0.5)
Example 2:
const result2: number = acos(1); Returns 0 (arccosine of 1)
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.
Param | Type | Description |
---|---|---|
num | number |
The number for which to calculate the arctangent in radians. |
Example
Example 1:
const result1: number = atan(1); Returns approximately 0.7853981633974483 (arctangent of 1)
Example 2:
const result2: number = atan(0); Returns 0 (arctangent of 0)
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.
Param | Type | Description |
---|---|---|
num | number |
The number for which to calculate the arccosecant in radians. |
Example
Example 1:
const result1: number = acosec(2); Returns approximately 1.5707963267948966 (arccosecant of 2)
Example 2:
const result2: number = acosec(1); Returns approximately 1.5707963267948966 (arccosecant of 1)
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.
Param | Type | Description |
---|---|---|
num | number |
The number for which to calculate the arcsecant in radians. |
Example
Example 1:
const result1: number = asec(2); Returns approximately 1.0471975511965979 (arcsecant of 2)
Example 2:
const result2: number = asec(1); Returns 0 (arcsecant of 1)
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.
Param | Type | Description |
---|---|---|
num | number |
The number for which to calculate the arccotangent in rad |