diff --git a/Conversions/BinaryToDecimal.js b/Conversions/BinaryToDecimal.js index d149de0df2..ae38a367a3 100644 --- a/Conversions/BinaryToDecimal.js +++ b/Conversions/BinaryToDecimal.js @@ -1,3 +1,9 @@ +/** + * Converts a binary string to a decimal number. + * + * @param {string} binaryString - The binary string to be converted to decimal. + * @returns {number} The decimal representation of the binary string. + */ export default function binaryToDecimal(binaryString) { let decimalNumber = 0 const binaryDigits = binaryString.split('').reverse() // Splits the binary number into reversed single digits diff --git a/Conversions/RGBToHex.js b/Conversions/RGBToHex.js index c44e9917aa..461fa098d2 100644 --- a/Conversions/RGBToHex.js +++ b/Conversions/RGBToHex.js @@ -1,3 +1,12 @@ +/** + * Converts RGB color values to a hexadecimal color code. + * + * @param {number} r - The red color value (0-255). + * @param {number} g - The green color value (0-255). + * @param {number} b - The blue color value (0-255). + * @returns {string} The hexadecimal color code representing the RGB values. + * @throws {TypeError} If any of the arguments is not a number. + */ function RGBToHex(r, g, b) { if (typeof r !== 'number' || typeof g !== 'number' || typeof b !== 'number') { throw new TypeError('argument is not a Number') diff --git a/Dynamic-Programming/UniquePaths.js b/Dynamic-Programming/UniquePaths.js index a37049b2f4..452e0ffcc8 100644 --- a/Dynamic-Programming/UniquePaths.js +++ b/Dynamic-Programming/UniquePaths.js @@ -12,7 +12,7 @@ * More info: https://leetcode.com/problems/unique-paths/ */ -/* +/** * @param {number} m * @param {number} n * @return {number} diff --git a/Dynamic-Programming/ZeroOneKnapsack.js b/Dynamic-Programming/ZeroOneKnapsack.js index 52a06aa130..bef3a3b6ae 100644 --- a/Dynamic-Programming/ZeroOneKnapsack.js +++ b/Dynamic-Programming/ZeroOneKnapsack.js @@ -3,6 +3,11 @@ * https://en.wikipedia.org/wiki/Knapsack_problem * * Time and Space Complexity: O(n*cap) + * @param {Array<[number, number]>} arr - An array of tuples representing the weights and values of items. + * @param {number} n - The number of items available. + * @param {number} cap - The capacity of the thief's bag. + * @param {Array>} cache - A 2D array to cache computed values for dynamic programming. + * @returns {number} The maximum value that can be stolen. */ const zeroOneKnapsack = (arr, n, cap, cache) => { // Base Case: No capacity or no items diff --git a/Graphs/BinaryLifting.js b/Graphs/BinaryLifting.js index b9a0116abc..de5e561872 100644 --- a/Graphs/BinaryLifting.js +++ b/Graphs/BinaryLifting.js @@ -1,7 +1,8 @@ /** * Author: Adrito Mukherjee + * @class BinaryLifting * Binary Lifting implementation in Javascript - * Binary Lifting is a technique that is used to find the kth ancestor of a node in a rooted tree with N nodes + * @classdesc Binary Lifting is a technique that is used to find the kth ancestor of a node in a rooted tree with N nodes * The technique requires preprocessing the tree in O(N log N) using dynamic programming * The technique can answer Q queries about kth ancestor of any node in O(Q log N) * It is faster than the naive algorithm that answers Q queries with complexity O(Q K) @@ -10,6 +11,12 @@ */ export class BinaryLifting { + /** + * Creates an instance of BinaryLifting. + * @template T + * @param {T} root + * @param {Array<[T, T]>} tree - The edges of the tree represented as an array of pairs. + */ constructor(root, tree) { this.root = root this.connections = new Map() diff --git a/Maths/ArmstrongNumber.js b/Maths/ArmstrongNumber.js index 8f861d8c15..581688b978 100644 --- a/Maths/ArmstrongNumber.js +++ b/Maths/ArmstrongNumber.js @@ -5,7 +5,8 @@ * An Armstrong number is equal to the sum of its own digits each raised to the power of the number of digits. * For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. * An Armstrong number is often called Narcissistic number. - * + * @param {number} num - The number to check if it is an Armstrong number. + * @returns {boolean} - True if the number is an Armstrong number, false otherwise. */ const armstrongNumber = (num) => { diff --git a/Maths/AverageMedian.js b/Maths/AverageMedian.js index f8f6c64b14..109d81aa2e 100644 --- a/Maths/AverageMedian.js +++ b/Maths/AverageMedian.js @@ -7,7 +7,11 @@ * if the length of the array is even number, the median value will be the average of the two middle numbers * else if the length of the array is odd number, the median value will be the middle number in the array */ - +/** + * Function to find the median value of an array of numbers. + * @param {number[]} + * @returns {number} - The median value of the array. + */ const averageMedian = (sourceArrayOfNumbers) => { const numbers = [...sourceArrayOfNumbers].sort(sortNumbers) const numLength = numbers.length @@ -16,7 +20,12 @@ const averageMedian = (sourceArrayOfNumbers) => { ? (numbers[numLength / 2 - 1] + numbers[numLength / 2]) / 2 : numbers[Math.floor(numLength / 2)] } - +/** + * Comparator function to sort numbers in ascending order. + * @param {number} num1 + * @param {number} num2 + * @returns {number} + */ const sortNumbers = (num1, num2) => num1 - num2 export { averageMedian } diff --git a/Maths/CheckKishnamurthyNumber.js b/Maths/CheckKishnamurthyNumber.js index 5098b0fa7f..d6a495e56f 100644 --- a/Maths/CheckKishnamurthyNumber.js +++ b/Maths/CheckKishnamurthyNumber.js @@ -6,6 +6,10 @@ */ // factorial utility method. +/** + * @param {Number} n + * @returns {Number} the factiorial of n + */ const factorial = (n) => { let fact = 1 while (n !== 0) { diff --git a/Maths/Coordinate.js b/Maths/Coordinate.js index b2276baa37..8741d58e22 100644 --- a/Maths/Coordinate.js +++ b/Maths/Coordinate.js @@ -4,12 +4,25 @@ Example: coorDistance(2,2,14,11) will return 15 Wikipedia reference: https://en.wikipedia.org/wiki/Geographical_distance#Flat-surface_formulae */ +/** + * @param {number} longitude1 - The longitude of the first point. + * @param {number} latitude1 - The latitude of the first point. + * @param {number} longitude2 - The longitude of the second point. + * @param {number} latitude2 - The latitude of the second point. + * @returns {number} - The Euclidean distance between the two points. + */ const euclideanDistance = (longitude1, latitude1, longitude2, latitude2) => { const width = longitude2 - longitude1 const height = latitude2 - latitude1 return Math.sqrt(width * width + height * height) } - +/* + * @param {number} longitude1 - The longitude of the first point. + * @param {number} latitude1 - The latitude of the first point. + * @param {number} longitude2 - The longitude of the second point. + * @param {number} latitude2 - The latitude of the second point. + * @returns {number} - The Manhattan distance between the two points. + */ const manhattanDistance = (longitude1, latitude1, longitude2, latitude2) => { const width = Math.abs(longitude2 - longitude1) const height = Math.abs(latitude2 - latitude1) diff --git a/Maths/EulersTotient.js b/Maths/EulersTotient.js index 09d05377af..025243e3d1 100644 --- a/Maths/EulersTotient.js +++ b/Maths/EulersTotient.js @@ -7,10 +7,12 @@ Complexity: O(sqrt(n)) */ - +/** + * + * @param {Number} n + * @returns {Number} count of numbers b/w 1 and n that are coprime to n + */ export const EulersTotient = (n) => { - // input: n: int - // output: phi(n): count of numbers b/w 1 and n that are coprime to n let res = n for (let i = 2; i * i <= n; i++) { if (n % i === 0) { diff --git a/Maths/EulersTotientFunction.js b/Maths/EulersTotientFunction.js index 387a93fa2b..d4e3b3c3fc 100644 --- a/Maths/EulersTotientFunction.js +++ b/Maths/EulersTotientFunction.js @@ -7,7 +7,12 @@ so EulersTotientFunction(n) (or phi(n)) is the count of numbers in {1,2,3,....,n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. */ - +/** + * + * @param {Number} x + * @param {Number} y + * @returns {Number} compute greatest common divisor for x and y + */ const gcdOfTwoNumbers = (x, y) => { // x is smaller than y // let gcd of x and y is gcdXY diff --git a/Maths/Factors.js b/Maths/Factors.js index 68bbde6d23..777fd5369b 100644 --- a/Maths/Factors.js +++ b/Maths/Factors.js @@ -6,7 +6,9 @@ * https://www.mathsisfun.com/definitions/factor.html * */ - +/** + * @param {Number} [number=0] + */ const factorsOfANumber = (number = 0) => { return Array.from(Array(number + 1).keys()).filter( (num) => number % num === 0 diff --git a/Maths/FindHcf.js b/Maths/FindHcf.js index 19105b5aa6..cfec179e0c 100644 --- a/Maths/FindHcf.js +++ b/Maths/FindHcf.js @@ -3,7 +3,12 @@ More about HCF: https://en.wikipedia.org/wiki/Greatest_common_divisor */ - +/** + * + * @param {Number} x + * @param {Number} y + * @returns {(string|number)} + */ const findHCF = (x, y) => { // If the input numbers are less than 1 return an error message. if (x < 1 || y < 1) { diff --git a/Maths/FindLcm.js b/Maths/FindLcm.js index 95ae2dc7f5..34eb651734 100644 --- a/Maths/FindLcm.js +++ b/Maths/FindLcm.js @@ -14,6 +14,12 @@ import { findHCF } from './FindHcf' // Find the LCM of two numbers. +/** + * + * @param {Number} num1 + * @param {Number} num2 + * @returns + */ const findLcm = (num1, num2) => { // If the input numbers are less than 1 return an error message. if (num1 < 1 || num2 < 1) { diff --git a/Maths/FriendlyNumbers.js b/Maths/FriendlyNumbers.js index f7440384b4..8d293dc6e0 100644 --- a/Maths/FriendlyNumbers.js +++ b/Maths/FriendlyNumbers.js @@ -4,7 +4,10 @@ Source: https://en.wikipedia.org/wiki/Friendly_number See also: https://mathworld.wolfram.com/FriendlyNumber.html#:~:text=The%20numbers%20known%20to%20be,numbers%20have%20a%20positive%20density. */ - +/** + * @param {Number} firstNumber, + * @param {Number} secondNumber + */ export const FriendlyNumbers = (firstNumber, secondNumber) => { // input: two integers // output: true if the two integers are friendly numbers, false if they are not friendly numbers @@ -22,11 +25,17 @@ export const FriendlyNumbers = (firstNumber, secondNumber) => { return abundancyIndex(firstNumber) === abundancyIndex(secondNumber) } - +/** + * @param {Number} number + */ function abundancyIndex(number) { return sumDivisors(number) / number } - +/** + * + * @param {Number} number + * @returns + */ function sumDivisors(number) { let runningSumDivisors = number for (let i = 0; i < number / 2; i++) { diff --git a/Maths/IsDivisible.js b/Maths/IsDivisible.js index 62c9f2e0a0..26319fad44 100644 --- a/Maths/IsDivisible.js +++ b/Maths/IsDivisible.js @@ -1,5 +1,11 @@ // Checks if a number is divisible by another number. - +/** + * + * @param {Number} num1 + * @param {Number} num2 + * @throws {TypeError} + * @returns {boolean} + */ export const isDivisible = (num1, num2) => { if (!Number.isFinite(num1) || !Number.isFinite(num2)) { throw new TypeError('Expected a valid real number') diff --git a/Maths/LinearSieve.js b/Maths/LinearSieve.js index 8092c9ebe4..7d43f385df 100644 --- a/Maths/LinearSieve.js +++ b/Maths/LinearSieve.js @@ -1,3 +1,8 @@ +/** + * + * @param {Number} n + * @returns {Number[]} array of prime numbers until number n + */ const LinearSieve = (n) => { /* * Calculates prime numbers till a number n diff --git a/Maths/MatrixExponentiationRecursive.js b/Maths/MatrixExponentiationRecursive.js index e86ceebe29..44c93f97b6 100644 --- a/Maths/MatrixExponentiationRecursive.js +++ b/Maths/MatrixExponentiationRecursive.js @@ -7,7 +7,11 @@ where: d is the dimension of the square matrix n is the power the matrix is raised to */ - +/** + * + * @param {Number} n + * @returns {Number[][]} + */ const Identity = (n) => { // Input: n: int // Output: res: Identity matrix of size n x n diff --git a/Maths/ModularBinaryExponentiationRecursive.js b/Maths/ModularBinaryExponentiationRecursive.js index 54665a3142..b7ca7f23db 100644 --- a/Maths/ModularBinaryExponentiationRecursive.js +++ b/Maths/ModularBinaryExponentiationRecursive.js @@ -5,7 +5,6 @@ Explanation: https://en.wikipedia.org/wiki/Exponentiation_by_squaring */ - const modularBinaryExponentiation = (a, n, m) => { // input: a: int, n: int, m: int // returns: (a^n) % m: int diff --git a/Maths/PerfectCube.js b/Maths/PerfectCube.js index 202cddafa5..036cad4dc5 100644 --- a/Maths/PerfectCube.js +++ b/Maths/PerfectCube.js @@ -3,6 +3,7 @@ * License: GPL-3.0 or later * * This uses `round` instead of `floor` or `trunc`, to guard against potential `cbrt` accuracy errors + * @param {Number} num */ const perfectCube = (num) => diff --git a/Recursive/KochSnowflake.js b/Recursive/KochSnowflake.js index 7b104da6e4..552963cd21 100644 --- a/Recursive/KochSnowflake.js +++ b/Recursive/KochSnowflake.js @@ -13,8 +13,17 @@ * https://natureofcode.com/book/chapter-8-fractals/ #84-the-koch-curve-and-the-arraylist-technique). */ -/** Class to handle the vector calculations. */ +/** Class to handle the vector calculations. + * @class Vector2 + */ export class Vector2 { + /** + * Creates a new Vector2 instance. + * @constructor + * @param {number} x - The x component of the vector. + * @param {number} y - The y component of the vector. + */ + constructor(x, y) { this.x = x this.y = y diff --git a/Recursive/LetterCombination.js b/Recursive/LetterCombination.js index 5131ebd857..950c799e7d 100644 --- a/Recursive/LetterCombination.js +++ b/Recursive/LetterCombination.js @@ -11,7 +11,7 @@ * More info: https://leetcode.com/problems/letter-combinations-of-a-phone-number/ */ -/* +/** * @param {string} digits * @returns {string[]} all the possible combinations */ diff --git a/Recursive/PalindromePartitioning.js b/Recursive/PalindromePartitioning.js index 9a5150f65d..bbaa10e20f 100644 --- a/Recursive/PalindromePartitioning.js +++ b/Recursive/PalindromePartitioning.js @@ -5,12 +5,23 @@ import { palindrome } from './Palindrome' * A palindrome partitioning partitions a string into palindromic substrings. * @see https://www.cs.columbia.edu/~sedwards/classes/2021/4995-fall/proposals/Palindrome.pdf */ +/** + * Returns all possible palindrome partitionings of a given string. + * @param {string} s + * @returns {string[][]} - Array of arrays containing all possible palindrome partitionings. + */ const partitionPalindrome = (s) => { const result = [] backtrack(s, [], result) return result } +/** + * Backtracking function to find palindrome partitionings. + * @param {string} s - The remaining part of the string to be checked for partitioning. + * @param {string[]} path - Current partitioning path. + * @param {string[][]} result - Array to store all valid palindrome partitionings. + */ const backtrack = (s, path, result) => { if (s.length === 0) { result.push([...path]) diff --git a/Recursive/SubsequenceRecursive.js b/Recursive/SubsequenceRecursive.js index c7bedcb7a6..e1627a1246 100644 --- a/Recursive/SubsequenceRecursive.js +++ b/Recursive/SubsequenceRecursive.js @@ -18,7 +18,14 @@ * https://en.wikipedia.org/wiki/Subsequence * https://en.wikipedia.org/wiki/Lexicographic_order */ - +/** + * Find all distinct, non-empty subsequences of a given string in lexicographical order using a recursive approach. + * @param {string} str + * @param {string} seq + * @param {number} low + * @param {string[]} [output=[]] + * @returns {string[]} + */ export const subsequence = (str, seq, low, output = []) => { if (low <= str.length && str.length !== 0) { output.push(seq) diff --git a/Recursive/TowerOfHanoi.js b/Recursive/TowerOfHanoi.js index 57c4db716c..df8d8c81c6 100644 --- a/Recursive/TowerOfHanoi.js +++ b/Recursive/TowerOfHanoi.js @@ -1,6 +1,14 @@ // wiki - https://en.wikipedia.org/wiki/Tower_of_Hanoi // Recursive Javascript function to solve tower of hanoi - +/** + * Solves the Tower of Hanoi problem recursively. + * @param {number} n - The number of disks to move. + * @param {string} from - The rod from which to move the disks. + * @param {string} to - The rod to which to move the disks. + * @param {string} aux - The auxiliary rod for moving disks. + * @param {string[]} [output=[]] - Optional array to store the sequence of moves. + * @returns {string[]} The sequence of moves to solve the Tower of Hanoi problem. + */ export function TowerOfHanoi(n, from, to, aux, output = []) { if (n === 1) { output.push(`Move disk 1 from rod ${from} to rod ${to}`) diff --git a/Search/BinarySearch.js b/Search/BinarySearch.js index c5477cb7b9..0ff6130022 100644 --- a/Search/BinarySearch.js +++ b/Search/BinarySearch.js @@ -6,7 +6,14 @@ * to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the * value is found or the interval is empty. */ - +/** + * Binary Search (Recursive) + * @param {number[]} arr - The sorted array to search within. + * @param {number} x - The value to search for in the array. + * @param {number} low - The lower bound index of the search interval (default is 0). + * @param {number} high - The upper bound index of the search interval (default is arr.length - 1). + * @returns {number} - The index of the found element if present, otherwise -1. + */ function binarySearchRecursive(arr, x, low = 0, high = arr.length - 1) { const mid = Math.floor(low + (high - low) / 2) @@ -28,6 +35,13 @@ function binarySearchRecursive(arr, x, low = 0, high = arr.length - 1) { return -1 } } +/** + * @param {number[]} arr - The sorted array to search within. + * @param {number} x - The value to search for in the array. + * @param {number} low - The lower bound index of the search interval (default is 0). + * @param {number} high - The upper bound index of the search interval (default is arr.length - 1). + * @returns {number} - The index of the found element if present, otherwise -1. + */ function binarySearchIterative(arr, x, low = 0, high = arr.length - 1) { while (high >= low) { const mid = Math.floor(low + (high - low) / 2) diff --git a/Search/ExponentialSearch.js b/Search/ExponentialSearch.js index d00a981645..0e06f6a8d5 100644 --- a/Search/ExponentialSearch.js +++ b/Search/ExponentialSearch.js @@ -8,7 +8,15 @@ * * */ - +/** + * Binary Search + * + * @param {number[]} arr - The array to search within. + * @param {number} value - The value to search for in the array. + * @param {number} floor - The lower bound index of the search range. + * @param {number} ceiling - The upper bound index of the search range. + * @returns {number} - The index of the found element if present, otherwise -1. + */ function binarySearch(arr, value, floor, ceiling) { // Middle index const mid = Math.floor((floor + ceiling) / 2) @@ -30,7 +38,13 @@ function binarySearch(arr, value, floor, ceiling) { return binarySearch(arr, value, mid + 1, ceiling) } } - +/** + * Exponential Search + * @param {number[]} arr - The array to search within. + * @param {number} length - The length of the array. + * @param {number} value - The value to search for in the array. + * @returns {number} - The index of the found element if present, otherwise -1. + */ function exponentialSearch(arr, length, value) { // If value is the first element of the array return this position if (arr[0] === value) { diff --git a/Search/FibonacciSearch.js b/Search/FibonacciSearch.js index 36459ec8de..8810862009 100644 --- a/Search/FibonacciSearch.js +++ b/Search/FibonacciSearch.js @@ -17,6 +17,11 @@ * * We define a function fibonacciSearch() that takes an array of numbers, * the item (number) to be searched for and the length of the items in the array + * @function fibonacciSearch + * @param {number[]} arr - The array of numbers to search within. + * @param {number} x - The number to search for in the array. + * @param {number} n - The length of the array. + * @returns {number} - The index of the found element if present, otherwise -1. ****************************************************************************/ export const fibonacciSearch = (arr, x, n) => { diff --git a/Search/InterpolationSearch.js b/Search/InterpolationSearch.js index 93f3b78b0e..7499155a4c 100644 --- a/Search/InterpolationSearch.js +++ b/Search/InterpolationSearch.js @@ -6,7 +6,9 @@ * -Worst case: O(n) * -O((log(log(n))) If the data are uniformly distributed * - * + * @param {number[]} arr - The sorted array to search in. + * @param {number} key - The value to search for in the array. + * @returns {number} - The index of the value in the array if found, otherwise -1 */ export function interpolationSearch(arr, key) { diff --git a/Search/JumpSearch.js b/Search/JumpSearch.js index a7b7b443e7..ce12bf2d0e 100644 --- a/Search/JumpSearch.js +++ b/Search/JumpSearch.js @@ -1,14 +1,23 @@ -/* The Jump Search algorithm allows to combine a linear search with a speed optimization. - * This means that instead of going 1 by 1, we will increase the step of √n and increase that - * step of √n which make the step getting bigger and bigger. - * The asymptotic analysis of Jump Search is o(√n). Like the binary search, it needs to be sorted. - * The advantage against binary search is that Jump Search traversed back only once. +/** + * The Jump Search algorithm allows combining a linear search with a speed optimization. + * Instead of searching one element at a time, it increases the step size by √n each time, + * making the step size progressively larger. The asymptotic analysis of Jump Search is O(√n). + * Similar to binary search, the array needs to be sorted for Jump Search to work correctly. + * The advantage of Jump Search over binary search is that it traverses back only once. + * + * @param {number[]} arr - The sorted array to search in. + * @param {number} value - The value to search for in the array. + * @returns {number} - The index of the value in the array if found, otherwise -1. + * + * @example + * const arr = [1, 3, 5, 7, 9, 11, 13, 15] + * const index = jumpSearch(arr, 7) // index will be 3 */ - const jumpSearch = (arr, value) => { const length = arr.length let step = Math.floor(Math.sqrt(length)) let lowerBound = 0 + while (arr[Math.min(step, length) - 1] < value) { lowerBound = step step += step @@ -24,6 +33,7 @@ const jumpSearch = (arr, value) => { return -1 } } + if (arr[lowerBound] === value) { return lowerBound } diff --git a/Search/LinearSearch.js b/Search/LinearSearch.js index 637ebc1589..ca722737d0 100644 --- a/Search/LinearSearch.js +++ b/Search/LinearSearch.js @@ -1,8 +1,19 @@ -/* - * Linear search or sequential search is a method for finding a target - * value within a list. It sequentially checks each element of the list - * for the target value until a match is found or until all the elements - * have been searched. +/** + * Linear search or sequential search is a method for finding a target value within a list. + * It sequentially checks each element of the list for the target value until a match is found + * or until all the elements have been searched. + * @function SearchArray + * @param {number} searchNum - The number to search for in the array. + * @param {number[]} ar - The array in which to search for the number. + * @param {(output: string) => void} [output=(v) => console.log(v)] - Optional callback function to handle output messages. + * @returns {void} + * + * @example + * // Example usage: + * const ar = [1, 2, 3, 4, 5, 6, 7, 8, 9] + * SearchArray(3, ar) // Output: The element was found at 3 + * SearchArray(4, ar) // Output: The element was found at 4 + * SearchArray(11, ar) // Output: The element not found */ function SearchArray(searchNum, ar, output = (v) => console.log(v)) { const position = Search(ar, searchNum) @@ -13,7 +24,18 @@ function SearchArray(searchNum, ar, output = (v) => console.log(v)) { } } -// Search “theArray” for the specified “key” value +/** + * Search for a key in an array using linear search. + * @function Search + * @param {number[]} theArray - The array to search. + * @param {number} key - The key to search for in the array. + * @returns {number} - The index of the key in the array if found, otherwise -1. + * + * @example + * const ar = [1, 2, 3, 4, 5, 6, 7, 8, 9] + * const index1 = Search(ar, 3) // index1 will be 2 + * const index2 = Search(ar, 10) // index2 will be -1 + */ function Search(theArray, key) { for (let n = 0; n < theArray.length; n++) { if (theArray[n] === key) { @@ -24,8 +46,3 @@ function Search(theArray, key) { } export { SearchArray, Search } - -// const ar = [1, 2, 3, 4, 5, 6, 7, 8, 9] -// SearchArray(3, ar) -// SearchArray(4, ar) -// SearchArray(11, ar) diff --git a/Search/QuickSelectSearch.js b/Search/QuickSelectSearch.js index c332af6721..a5274c4826 100644 --- a/Search/QuickSelectSearch.js +++ b/Search/QuickSelectSearch.js @@ -11,6 +11,20 @@ * * [Reference](http://en.wikipedia.org/wiki/Quickselect) */ +/** + * @function quickSelectSearch + * @param {number[]} array - The array of numbers to select the `k` smallest elements from. + * @param {number} k - The number of smallest elements to select. + * @returns {number[]} - A slice of the `k` smallest elements from the array. + * @throws {Error} - Throws an error if the array is empty or if `k` is greater than or equal to the array length. + * @example + * const arr = [1121111, 21, 333, 41, 5, 66, 7777, 28, 19, 11110] + * const result1 = quickSelectSearch(arr, 5) // [19, 21, 28, 41, 5] + * const result2 = quickSelectSearch(arr, 2) // [19, 5] + * const result3 = quickSelectSearch(arr, 7) // [19, 5, 21, 41, 28, 66, 333] + * + * @see {@link http://en.wikipedia.org/wiki/Quickselect} + */ export function quickSelectSearch(array, k) { if (!array || array.length <= k) { throw new Error('Invalid arguments') diff --git a/Search/RabinKarp.js b/Search/RabinKarp.js index e6d6394ede..05991858e8 100644 --- a/Search/RabinKarp.js +++ b/Search/RabinKarp.js @@ -12,6 +12,20 @@ * * [Reference](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm) */ +/** + * @param {string} text - The text string in which to search for the pattern. + * @param {string} pattern - The pattern string to search for in the text. + * @returns {number[]} - An array of indices where the pattern is found in the text. Returns an empty array if the pattern is not found. + * + * @example + * // Example usage: + * const text = 'abracadabra' + * const pattern = 'cad' + * const indices = rabinKarpSearch(text, pattern) + * console.log(indices) // Output: [3] + * + * @see {@link https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm} + */ const BASE = 256 // The number of characters in the alphabet const MOD = 997 // A prime number used for the hash function diff --git a/Search/StringSearch.js b/Search/StringSearch.js index cc3ad737a7..2e78662757 100644 --- a/Search/StringSearch.js +++ b/Search/StringSearch.js @@ -1,7 +1,12 @@ /* * String Search */ - +/** + * Builds a prefix table for String where table[i] store prefix of lengest prefix of + * substring str[0..i] + * @param {string} str - The word to build the prefix table for. + * @returns {number[]} - The prefix table for the word. + */ function makeTable(str) { // create a table of size equal to the length of `str` // table[i] will store the prefix of the longest prefix of the substring str[0..i] @@ -35,6 +40,11 @@ function makeTable(str) { } // Find all the words that matches in a given string `str` +/** + * @param {string} str - The main text string to search within. + * @param {string} word - The word to search for within the text. + * @returns {number[]} - An array of indices where the word matches occur in the text. + */ export function stringSearch(str, word) { // find the prefix table in O(n) const prefixes = makeTable(word) diff --git a/Search/TernarySearch.js b/Search/TernarySearch.js index ea0d049341..c9e6209841 100644 --- a/Search/TernarySearch.js +++ b/Search/TernarySearch.js @@ -10,6 +10,14 @@ * * Reference: https://www.geeksforgeeks.org/ternary-search/ */ +/** + * + * @param {number[]} arr - The sorted array to search in. + * @param {number} key - The key to search for. + * @param {number} [low=0] - The lowest index of the search range. + * @param {number} [high=arr.length - 1] - The highest index of the search range. + * @returns {number} - The index of the key if found, otherwise -1. + */ function ternarySearchRecursive(arr, key, low = 0, high = arr.length - 1) { if (high >= low) { @@ -46,7 +54,13 @@ function ternarySearchRecursive(arr, key, low = 0, high = arr.length - 1) { return -1 } } - +/** + * @param {number[]} arr - The sorted array to search in. + * @param {number} key - The key to search for. + * @param {number} [low=0] - The lowest index of the search range. + * @param {number} [high=arr.length - 1] - The highest index of the search range. + * @returns {number} - The index of the key if found, otherwise -1. + */ function ternarySearchIterative(arr, key, low = 0, high = arr.length - 1) { while (high >= low) { // find the mid1 and mid2 diff --git a/Search/UnionFind.js b/Search/UnionFind.js index 5b234da9a1..0b956ec8fb 100644 --- a/Search/UnionFind.js +++ b/Search/UnionFind.js @@ -13,6 +13,8 @@ * especially for register allocation problems. * * you can learn more on disjoint-set / union–find data structure at https://en.wikipedia.org/wiki/Disjoint-set_data_structure + * @param {number} n The number of distinct groups to initialize the Union Find data structure. + * @param {function(number): number} [key] Optional key function that maps indices of groups. Default is the identity function. */ function UnionFind(n, key) { if (!(this instanceof UnionFind)) return new UnionFind(n) diff --git a/Sorts/AlphaNumericalSort.js b/Sorts/AlphaNumericalSort.js index fb6be8f424..9387bc0d78 100644 --- a/Sorts/AlphaNumericalSort.js +++ b/Sorts/AlphaNumericalSort.js @@ -17,9 +17,14 @@ 2. z11 P.S. use this function, as there are a lot of implementations on the stackoverflow and other forums, but many of them don't work correctly (can't pass all my tests) - + */ - +/** + * @param {string} a The first string to compare. + * @param {string} b The second string to compare. + * @returns {number} Returns a number indicating whether the first string comes before, after, or is the same as the second string in sort order. + * -1 if a comes before b, 1 if a comes after b, and 0 if they are the same. + */ const alphaNumericalSort = (a, b) => { /* https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare diff --git a/Sorts/BeadSort.js b/Sorts/BeadSort.js index 6a6f69398d..f4de1ac766 100644 --- a/Sorts/BeadSort.js +++ b/Sorts/BeadSort.js @@ -7,6 +7,9 @@ * NOTE: It only works for arrays of positive integers. * * Wikipedia: https://en.wikipedia.org/wiki/Bead_sort + * @param {number[]} sequence An array of positive integers to be sorted. + * @returns {number[]} Returns a sorted array of positive integers. + * @throws {RangeError} Throws a RangeError if the input sequence contains any negative integers. */ export function beadSort(sequence) { /* Let's ensure our sequence has only Positive Integers */ diff --git a/Sorts/BogoSort.js b/Sorts/BogoSort.js index eeb4f7feeb..313cacb591 100644 --- a/Sorts/BogoSort.js +++ b/Sorts/BogoSort.js @@ -1,5 +1,7 @@ /** * Checks whether the given array is sorted in ascending order. + * @param {String[]} + * @returns {boolean} Returns true if the array is sorted in ascending order, false otherwise. */ export function isSorted(array) { const length = array.length @@ -13,6 +15,7 @@ export function isSorted(array) { /** * Shuffles the given array randomly in place. + * @param {any[]} */ function shuffle(array) { for (let i = array.length - 1; i; i--) { diff --git a/Sorts/BubbleSort.js b/Sorts/BubbleSort.js index 5571fac047..48d99c7133 100644 --- a/Sorts/BubbleSort.js +++ b/Sorts/BubbleSort.js @@ -15,6 +15,8 @@ /** * Using 2 for loops. + * @param {number[]} items The array to be sorted. + * @returns {number[]} The sorted array. */ export function bubbleSort(items) { const length = items.length @@ -42,6 +44,8 @@ export function bubbleSort(items) { /** * Using a while loop and a for loop. + * @param {number[]} + * @returns {number[]} The sorted array. */ export function alternativeBubbleSort(arr) { let swapped = true diff --git a/Sorts/CocktailShakerSort.js b/Sorts/CocktailShakerSort.js index 033c7c461a..2079b6753c 100644 --- a/Sorts/CocktailShakerSort.js +++ b/Sorts/CocktailShakerSort.js @@ -7,6 +7,9 @@ * * Wikipedia (Cocktail Shaker Sort): https://en.wikipedia.org/wiki/Cocktail_shaker_sort * Wikipedia (Bubble Sort): https://en.wikipedia.org/wiki/Bubble_sort + * + * @param {number[]} + * @returns {number[]} The sorted array. */ export function cocktailShakerSort(items) { for (let i = items.length - 1; i > 0; i--) { diff --git a/Sorts/CountingSort.js b/Sorts/CountingSort.js index c7d495d92f..1a2e54a408 100644 --- a/Sorts/CountingSort.js +++ b/Sorts/CountingSort.js @@ -6,6 +6,11 @@ * * Wikipedia: https://en.wikipedia.org/wiki/Counting_sort * Animated Visual: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html + * + * @param {number[]} arr The array to be sorted. + * @param {number} min The minimum value in the array. + * @param {number} max The maximum value in the array. + * @returns {number[]} The sorted array. */ export const countingSort = (arr, min, max) => { diff --git a/Sorts/FindSecondLargestElement.js b/Sorts/FindSecondLargestElement.js index 504b7e1192..b7174085da 100644 --- a/Sorts/FindSecondLargestElement.js +++ b/Sorts/FindSecondLargestElement.js @@ -8,7 +8,11 @@ * Resources: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set */ - +/** + * Finds the second largest element in an array of numbers while filtering out duplicate values. + * @param {number[]} array The array of numbers. + * @returns {number} The second largest element in the array. + */ const secondLargestElement = (array) => { const largestElement = Math.max(...array) let element = -Number.MAX_VALUE diff --git a/Sorts/FisherYatesShuffle.js b/Sorts/FisherYatesShuffle.js index 214cb5baa7..d892ff1449 100644 --- a/Sorts/FisherYatesShuffle.js +++ b/Sorts/FisherYatesShuffle.js @@ -1,3 +1,6 @@ +/** + * @returns {Array} The shuffled array. + */ export const shuffle = (array) => { let maxLength = array.length let temp diff --git a/String/BoyerMoore.js b/String/BoyerMoore.js index 6ec8108b71..542b3cace2 100644 --- a/String/BoyerMoore.js +++ b/String/BoyerMoore.js @@ -1,14 +1,14 @@ -/* - * - * - *Implementation of the Boyer-Moore String Search Algorithm. - *The Boyer–Moore string search algorithm allows linear time in - *search by skipping indices when searching inside a string for a pattern. - * - * - * - * - **/ +/** + * Implementation of the Boyer-Moore String Search Algorithm. + * The Boyer–Moore string search algorithm allows linear time search by skipping indices + * when searching inside a string for a pattern. + */ + +/** + * Builds the bad match table for the Boyer-Moore algorithm based on the pattern. + * @param {string} str The pattern string for which the bad match table is built. + * @returns {Object} The bad match table object containing characters and their corresponding offsets. + */ const buildBadMatchTable = (str) => { const tableObj = {} const strLength = str.length @@ -21,6 +21,12 @@ const buildBadMatchTable = (str) => { return tableObj } +/** + * Performs the Boyer-Moore string search algorithm to find a pattern in a given string. + * @param {string} str The string in which to search for the pattern. + * @param {string} pattern The pattern string to search for in the main string. + * @returns {number} The index at which the pattern is found in the string, or -1 if not found. + */ const boyerMoore = (str, pattern) => { const badMatchTable = buildBadMatchTable(pattern) let offset = 0 @@ -46,4 +52,5 @@ const boyerMoore = (str, pattern) => { } return -1 } + export { boyerMoore } diff --git a/String/CheckPalindrome.js b/String/CheckPalindrome.js index a717ccd5f4..e904f136c7 100644 --- a/String/CheckPalindrome.js +++ b/String/CheckPalindrome.js @@ -1,5 +1,11 @@ -// Palindrome check is case sensitive; i.e. Aba is not a palindrome -// input is a string +/** + * Checks if a string is a palindrome. + * A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. + * Palindrome check is case sensitive; i.e., "Aba" is not considered a palindrome. + * @param {string} str The input string to be checked for palindrome. + * @returns {string} Returns 'Palindrome' if the input string is a palindrome, + * 'Not a Palindrome' if it is not, or an error message if the input is not a valid string. + */ const checkPalindrome = (str) => { // check that input is a string if (typeof str !== 'string') { diff --git a/String/CheckRearrangePalindrome.js b/String/CheckRearrangePalindrome.js index c3feb59f16..54b28133bb 100644 --- a/String/CheckRearrangePalindrome.js +++ b/String/CheckRearrangePalindrome.js @@ -3,7 +3,9 @@ * Receives a string and returns whether it can be rearranged to become a palindrome or not * The string can only be a palindrome if the count of ALL characters is even or if the ONLY ONE character count is odd * Input is a string - * + * @param {string} str The input string to be checked for palindrome rearrangement. + * @returns {boolean|string} Returns true if the string can be rearranged to form a palindrome, + * false if it cannot, or an error message if the input is not a valid string. **/ export const palindromeRearranging = (str) => { diff --git a/Trees/BreadthFirstTreeTraversal.js b/Trees/BreadthFirstTreeTraversal.js index a2524c18fd..66eaabf939 100644 --- a/Trees/BreadthFirstTreeTraversal.js +++ b/Trees/BreadthFirstTreeTraversal.js @@ -1,9 +1,11 @@ -/* - Breadth First Tree Traversal or level order traversal implementation in javascript - Author: @GerardUbuntu -*/ - +/** + * Represents a node in a binary tree. + */ class Node { + /** + * Creates a new node with the specified data. + * @param {*} data The data to be stored in the node. + */ constructor(data) { this.data = data this.left = null @@ -11,11 +13,21 @@ class Node { } } +/** + * Represents a binary tree data structure. + */ class BinaryTree { + /** + * Creates a new binary tree with an empty root. + */ constructor() { this.root = null } + /** + * Performs breadth-first traversal of the binary tree iteratively. + * @returns {Array} An array containing the data of nodes visited in breadth-first order. + */ breadthFirstIterative() { const traversal = [] if (this.root) { @@ -34,6 +46,10 @@ class BinaryTree { return traversal } + /** + * Performs breadth-first traversal of the binary tree recursively. + * @returns {Array} An array containing the data of nodes visited in breadth-first order. + */ breadthFirstRecursive() { const traversal = [] const h = this.getHeight(this.root) @@ -43,7 +59,11 @@ class BinaryTree { return traversal } - // Computing the height of the tree + /** + * Computes the height of the tree starting from the specified node. + * @param {Node} node The node from which to compute the height. + * @returns {number} The height of the tree. + */ getHeight(node) { if (node === null) { return 0 @@ -53,6 +73,12 @@ class BinaryTree { return lheight > rheight ? lheight + 1 : rheight + 1 } + /** + * Traverses the specified level of the tree and adds nodes' data to the traversal array. + * @param {Node} node The current node being traversed. + * @param {number} levelRemaining The remaining level to traverse. + * @param {Array} traversal The array to store the traversal result. + */ traverseLevel(node, levelRemaining, traversal) { if (node === null) { return diff --git a/Trees/DepthFirstSearch.js b/Trees/DepthFirstSearch.js index 7c67afc95e..c929137c1c 100644 --- a/Trees/DepthFirstSearch.js +++ b/Trees/DepthFirstSearch.js @@ -4,7 +4,12 @@ * DFS Algorithm for traversing or searching graph data structures. */ -// traverses a give tree from specified root's value +/** + * Traverses a given tree using Depth-First Search (DFS) algorithm from the specified root's value. + * @param {Array} tree The tree data structure represented as an array of nodes. + * @param {number} rootValue The value of the root node from which traversal starts. + * @returns {Array} An array containing the values of nodes traversed in DFS order. + */ function traverseDFS(tree, rootValue) { const stack = [] const res = [] @@ -23,7 +28,12 @@ function traverseDFS(tree, rootValue) { } return res.reverse() } - +/** + * Searches for a node with the specified value in the given tree using Depth-First Search (DFS) algorithm. + * @param {Array} tree The tree data structure represented as an array of nodes. + * @param {number} value The value to search for in the tree nodes. + * @returns {Object|null} The node object if found, or null if the value is not found in the tree. + */ function searchDFS(tree, value) { const stack = [] stack.push(tree[0]) diff --git a/Trees/FenwickTree.js b/Trees/FenwickTree.js index d84b4f0f66..d50abea067 100644 --- a/Trees/FenwickTree.js +++ b/Trees/FenwickTree.js @@ -5,6 +5,12 @@ */ class FenwickTree { + /** + * Constructs a Fenwick Tree. + * @param {Array} fenwickArray The Fenwick Tree array to be initialized. + * @param {Array} array The input array whose prefix sum is to be calculated. + * @param {number} n The size of the input array. + */ constructor(feneickArray, array, n) { for (let i = 1; i <= n; i++) { feneickArray[i] = 0 @@ -14,6 +20,13 @@ class FenwickTree { } } + /** + * Updates the Fenwick Tree with a new value at the specified index. + * @param {Array} fenwickArray The Fenwick Tree array. + * @param {number} n The size of the Fenwick Tree array. + * @param {number} index The index at which the value is updated. + * @param {number} value The new value to be added at the index. + */ update(feneickArray, n, index, value) { index = index + 1 while (index <= n) {