diff --git a/.husky/pre-commit b/.husky/pre-commit index 35ea7e3c08..037dbe870a 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,5 +1,5 @@ #!/bin/sh . "$(dirname "$0")/_/husky.sh" -npm run style +npm run check-style npm run test diff --git a/Conversions/DateDayDifference.js b/Conversions/DateDayDifference.js index 770b64c174..726a634253 100644 --- a/Conversions/DateDayDifference.js +++ b/Conversions/DateDayDifference.js @@ -6,54 +6,28 @@ Algorithm & Explanation : https://ncalculators.com/time-date/date-difference-calculator.htm */ -// Internal method for make calculations easier -const isLeap = (year) => { - if (year % 400 === 0) return true - else if (year % 100 === 0) return false - else if (year % 4 === 0) return true - else return false -} +import { isLeapYear } from '../Maths/LeapYear' +import { parseDate } from '../Timing-Functions/ParseDate' + const DateToDay = (dd, mm, yyyy) => { - return Math.floor( + return ( 365 * (yyyy - 1) + - (yyyy - 1) / 4 - - (yyyy - 1) / 100 + - (yyyy - 1) / 400 + - dd + - (367 * mm - 362) / 12 + - (mm <= 2 ? 0 : isLeap(yyyy) ? -1 : -2) + Math.floor((yyyy - 1) / 4) - + Math.floor((yyyy - 1) / 100) + + Math.floor((yyyy - 1) / 400) + + dd + + Math.floor((367 * mm - 362) / 12) + + (mm <= 2 ? 0 : isLeapYear(yyyy) ? -1 : -2) ) } const DateDayDifference = (date1, date2) => { - // firstly, check that both input are string or not. - if (typeof date1 !== 'string' || typeof date2 !== 'string') { - return new TypeError('Argument is not a string.') - } - // extract the first date - const [firstDateDay, firstDateMonth, firstDateYear] = date1 - .split('/') - .map((ele) => Number(ele)) - // extract the second date - const [secondDateDay, secondDateMonth, secondDateYear] = date2 - .split('/') - .map((ele) => Number(ele)) - // check the both data are valid or not. - if ( - firstDateDay < 0 || - firstDateDay > 31 || - firstDateMonth > 12 || - firstDateMonth < 0 || - secondDateDay < 0 || - secondDateDay > 31 || - secondDateMonth > 12 || - secondDateMonth < 0 - ) { - return new TypeError('Date is not valid.') - } + const firstDate = parseDate(date1) + const secondDate = parseDate(date2) + return Math.abs( - DateToDay(secondDateDay, secondDateMonth, secondDateYear) - - DateToDay(firstDateDay, firstDateMonth, firstDateYear) + DateToDay(secondDate.day, secondDate.month, secondDate.year) - + DateToDay(firstDate.day, firstDate.month, firstDate.year) ) } diff --git a/Conversions/DateToDay.js b/Conversions/DateToDay.js index 378489e50e..96ec01e82d 100644 --- a/Conversions/DateToDay.js +++ b/Conversions/DateToDay.js @@ -12,6 +12,8 @@ Algorithm & Explanation : https://en.wikipedia.org/wiki/Zeller%27s_congruence */ +import { parseDate } from '../Timing-Functions/ParseDate' + // Array holding name of the day: Saturday - Sunday - Friday => 0 - 1 - 6 const daysNameArr = [ 'Saturday', @@ -25,15 +27,10 @@ const daysNameArr = [ const DateToDay = (date) => { // firstly, check that input is a string or not. - if (typeof date !== 'string') { - return new TypeError('Argument is not a string.') - } - // extract the date - let [day, month, year] = date.split('/').map((x) => Number(x)) - // check the data are valid or not. - if (day < 1 || day > 31 || month > 12 || month < 1) { - return new TypeError('Date is not valid.') - } + const dateStruct = parseDate(date) + let year = dateStruct.year + let month = dateStruct.month + let day = dateStruct.day // In case of Jan and Feb: // Year: we consider it as previous year diff --git a/Conversions/RailwayTimeConversion.js b/Conversions/RailwayTimeConversion.js index fd4f9a5dad..b499023223 100644 --- a/Conversions/RailwayTimeConversion.js +++ b/Conversions/RailwayTimeConversion.js @@ -18,14 +18,14 @@ const RailwayTimeConversion = (timeString) => { // firstly, check that input is a string or not. if (typeof timeString !== 'string') { - return new TypeError('Argument is not a string.') + throw new TypeError('Argument is not a string.') } // split the string by ':' character. const [hour, minute, secondWithShift] = timeString.split(':') // split second and shift value. const [second, shift] = [ - secondWithShift.substr(0, 2), - secondWithShift.substr(2) + secondWithShift.substring(0, 2), + secondWithShift.substring(2) ] // convert shifted time to not-shift time(Railway time) by using the above explanation. if (shift === 'PM') { diff --git a/Conversions/test/DateDayDiffernce.test.js b/Conversions/test/DateDayDiffernce.test.js index 713ee1272e..a0f8834593 100644 --- a/Conversions/test/DateDayDiffernce.test.js +++ b/Conversions/test/DateDayDiffernce.test.js @@ -1,21 +1,36 @@ import { DateDayDifference } from '../DateDayDifference' -test('The difference between 17/08/2002 & 10/10/2020 is 6630', () => { - const res = DateDayDifference('17/08/2002', '10/10/2020') - expect(res).toBe(6630) -}) - -test('The difference between 18/02/2001 & 16/03/2022 is 7696', () => { - const res = DateDayDifference('18/02/2001', '16/03/2022') - expect(res).toBe(7696) -}) +describe('DateDayDifference', () => { + it.each([ + ['17/08/2002', '10/10/2020', 6629], + ['18/02/2001', '16/03/2022', 7696], + ['11/11/2011', '12/12/2012', 397], + ['01/01/2001', '16/03/2011', 3726], + ['04/03/2024', '04/03/2024', 0], + ['03/03/2024', '04/03/2024', 1], + ['02/03/2024', '04/03/2024', 2], + ['01/03/2024', '04/03/2024', 3], + ['29/02/2024', '04/03/2024', 4], + ['04/03/2024', '04/03/2025', 365], + ['04/03/2023', '04/03/2024', 366] + ])( + 'The difference between %s and %s is %i', + (firstDate, secondDate, expected) => { + expect(DateDayDifference(firstDate, secondDate)).toBe(expected) + expect(DateDayDifference(secondDate, firstDate)).toBe(expected) + } + ) -test('The difference between 11/11/2011 & 12/12/2012 is 398', () => { - const res = DateDayDifference('11/11/2011', '12/12/2012') - expect(res).toBe(398) -}) + it('should throw when any input is not a string', () => { + expect(() => DateDayDifference(10102024, '11/10/2024')).toThrowError() + expect(() => DateDayDifference('11/10/2024', 10102024)).toThrowError() + }) -test('The difference between 01/01/2001 & 16/03/2011 is 3727', () => { - const res = DateDayDifference('01/01/2001', '16/03/2011') - expect(res).toBe(3727) + it.each(['32/01/2000', '00/01/2000', '15/00/2000', '15/13/2000'])( + 'should throw when input is not a correct date %s', + (wrongDate) => { + expect(() => DateDayDifference(wrongDate, '04/03/2024')).toThrowError() + expect(() => DateDayDifference('04/03/2024', wrongDate)).toThrowError() + } + ) }) diff --git a/Conversions/test/DateToDay.test.js b/Conversions/test/DateToDay.test.js index f0809821db..38b63d33da 100644 --- a/Conversions/test/DateToDay.test.js +++ b/Conversions/test/DateToDay.test.js @@ -1,35 +1,28 @@ import { DateToDay } from '../DateToDay' -test('The date 18/02/2001 is Sunday', () => { - const res = DateToDay('18/02/2001') - expect(res).toBe('Sunday') -}) - -test('The date 18/12/2020 is Friday', () => { - const res = DateToDay('18/12/2020') - expect(res).toBe('Friday') -}) +describe('DateToDay', () => { + it.each([ + ['18/02/2001', 'Sunday'], + ['18/12/2020', 'Friday'], + ['12/12/2012', 'Wednesday'], + ['01/01/2001', 'Monday'], + ['1/1/2020', 'Wednesday'], + ['2/3/2014', 'Sunday'], + ['28/2/2017', 'Tuesday'], + ['02/03/2024', 'Saturday'], + ['29/02/2024', 'Thursday'] + ])('%s is %s', (date, day) => { + expect(DateToDay(date)).toBe(day) + }) -test('The date 12/12/2012 is Wednesday', () => { - const res = DateToDay('12/12/2012') - expect(res).toBe('Wednesday') -}) -test('The date 01/01/2001 is Monday', () => { - const res = DateToDay('01/01/2001') - expect(res).toBe('Monday') -}) - -test('The date 1/1/2020 is Wednesday', () => { - const res = DateToDay('1/1/2020') - expect(res).toBe('Wednesday') -}) - -test('The date 2/3/2014 is Sunday', () => { - const res = DateToDay('2/3/2014') - expect(res).toBe('Sunday') -}) + it('should throw when input is not a string', () => { + expect(() => DateToDay(100)).toThrowError() + }) -test('The date 28/2/2017 is Tuesday', () => { - const res = DateToDay('28/2/2017') - expect(res).toBe('Tuesday') + it.each(['32/01/2000', '00/01/2000', '15/00/2000', '15/13/2000'])( + 'should throw when input is not a correct date %s', + (wrongDate) => { + expect(() => DateToDay(wrongDate)).toThrowError() + } + ) }) diff --git a/Conversions/test/RailwayTimeConversion.test.js b/Conversions/test/RailwayTimeConversion.test.js index 0e49af3b7f..6579420049 100644 --- a/Conversions/test/RailwayTimeConversion.test.js +++ b/Conversions/test/RailwayTimeConversion.test.js @@ -19,3 +19,7 @@ test('The RailwayTimeConversion of 11:20:00PM is 23:20:00', () => { const res = RailwayTimeConversion('11:20:00PM') expect(res).toEqual('23:20:00') }) + +test('The RailwayTimeConversion throws when input is not a string', () => { + expect(() => RailwayTimeConversion(1120)).toThrowError() +}) diff --git a/DIRECTORY.md b/DIRECTORY.md index 8b51ce3bf7..59f6273bf2 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -260,7 +260,6 @@ * [SquareRootLogarithmic](Maths/SquareRootLogarithmic.js) * [SumOfDigits](Maths/SumOfDigits.js) * [SumOfGeometricProgression](Maths/SumOfGeometricProgression.js) - * [TwinPrime](Maths/TwinPrime.js) * [TwoSum](Maths/TwoSum.js) * [Volume](Maths/Volume.js) * [WhileLoopFactorial](Maths/WhileLoopFactorial.js) @@ -296,7 +295,6 @@ * **Recursive** * [BinaryEquivalent](Recursive/BinaryEquivalent.js) * [BinarySearch](Recursive/BinarySearch.js) - * [EucledianGCD](Recursive/EucledianGCD.js) * [Factorial](Recursive/Factorial.js) * [FibonacciNumberRecursive](Recursive/FibonacciNumberRecursive.js) * [FloodFill](Recursive/FloodFill.js) diff --git a/Data-Structures/Array/Reverse.js b/Data-Structures/Array/Reverse.js index 79a789c017..ca08f35f8a 100644 --- a/Data-Structures/Array/Reverse.js +++ b/Data-Structures/Array/Reverse.js @@ -7,11 +7,9 @@ const Reverse = (arr) => { // limit specifies the amount of Reverse actions - for (let i = 0, j = arr.length - 1; i < arr.length / 2; i++, j--) { - const temp = arr[i] - arr[i] = arr[j] - arr[j] = temp - } + for (let i = 0, j = arr.length - 1; i < arr.length / 2; i++, j--) + [arr[i], arr[j]] = [arr[j], arr[i]] + return arr } export { Reverse } diff --git a/Data-Structures/Queue/CircularQueue.js b/Data-Structures/Queue/CircularQueue.js index 27f2196780..c716251668 100644 --- a/Data-Structures/Queue/CircularQueue.js +++ b/Data-Structures/Queue/CircularQueue.js @@ -77,7 +77,7 @@ class CircularQueue { // Displays the length of queue length() { - return this.queue.length - 1 + return this.checkEmpty() ? 0 : this.queue.length - 1 } // Display the top most value of queue diff --git a/Data-Structures/Stack/Stack.js b/Data-Structures/Stack/Stack.js index d3001e8020..d8531fdebf 100644 --- a/Data-Structures/Stack/Stack.js +++ b/Data-Structures/Stack/Stack.js @@ -8,8 +8,8 @@ // Functions: push, pop, peek, view, length // Creates a stack constructor -const Stack = (function () { - function Stack() { +class Stack { + constructor() { // The top of the Stack this.top = 0 // The array representation of the stack @@ -17,13 +17,13 @@ const Stack = (function () { } // Adds a value onto the end of the stack - Stack.prototype.push = function (value) { + push(value) { this.stack[this.top] = value this.top++ } // Removes and returns the value at the end of the stack - Stack.prototype.pop = function () { + pop() { if (this.top === 0) { return 'Stack is Empty' } @@ -35,23 +35,21 @@ const Stack = (function () { } // Returns the size of the stack - Stack.prototype.size = function () { + size() { return this.top } // Returns the value at the end of the stack - Stack.prototype.peek = function () { + peek() { return this.stack[this.top - 1] } // To see all the elements in the stack - Stack.prototype.view = function (output = (value) => console.log(value)) { + view(output = (value) => console.log(value)) { for (let i = 0; i < this.top; i++) { output(this.stack[i]) } } - - return Stack -})() +} export { Stack } diff --git a/Data-Structures/Tree/AVLTree.js b/Data-Structures/Tree/AVLTree.js index e5abbf3e55..dd673a9330 100644 --- a/Data-Structures/Tree/AVLTree.js +++ b/Data-Structures/Tree/AVLTree.js @@ -31,8 +31,8 @@ let utils * @argument comp - A function used by AVL Tree For Comparison * If no argument is sent it uses utils.comparator */ -const AVLTree = (function () { - function _avl(comp) { +class AVLTree { + constructor(comp) { /** @public comparator function */ this._comp = undefined this._comp = comp !== undefined ? comp : utils.comparator() @@ -43,162 +43,6 @@ const AVLTree = (function () { this.size = 0 } - // creates new Node Object - const Node = function (val) { - this._val = val - this._left = null - this._right = null - this._height = 1 - } - - // get height of a node - const getHeight = function (node) { - if (node == null) { - return 0 - } - return node._height - } - - // height difference or balance factor of a node - const getHeightDifference = function (node) { - return node == null ? 0 : getHeight(node._left) - getHeight(node._right) - } - - // update height of a node based on children's heights - const updateHeight = function (node) { - if (node == null) { - return - } - node._height = Math.max(getHeight(node._left), getHeight(node._right)) + 1 - } - - // Helper: To check if the balanceFactor is valid - const isValidBalanceFactor = (balanceFactor) => - [0, 1, -1].includes(balanceFactor) - - // rotations of AVL Tree - const leftRotate = function (node) { - const temp = node._right - node._right = temp._left - temp._left = node - updateHeight(node) - updateHeight(temp) - return temp - } - const rightRotate = function (node) { - const temp = node._left - node._left = temp._right - temp._right = node - updateHeight(node) - updateHeight(temp) - return temp - } - - // check if tree is balanced else balance it for insertion - const insertBalance = function (node, _val, balanceFactor, tree) { - if (balanceFactor > 1 && tree._comp(_val, node._left._val) < 0) { - return rightRotate(node) // Left Left Case - } - if (balanceFactor < 1 && tree._comp(_val, node._right._val) > 0) { - return leftRotate(node) // Right Right Case - } - if (balanceFactor > 1 && tree._comp(_val, node._left._val) > 0) { - node._left = leftRotate(node._left) // Left Right Case - return rightRotate(node) - } - node._right = rightRotate(node._right) - return leftRotate(node) - } - - // check if tree is balanced after deletion - const delBalance = function (node) { - const balanceFactor1 = getHeightDifference(node) - if (isValidBalanceFactor(balanceFactor1)) { - return node - } - if (balanceFactor1 > 1) { - if (getHeightDifference(node._left) >= 0) { - return rightRotate(node) // Left Left - } - node._left = leftRotate(node._left) - return rightRotate(node) // Left Right - } - if (getHeightDifference(node._right) > 0) { - node._right = rightRotate(node._right) - return leftRotate(node) // Right Left - } - return leftRotate(node) // Right Right - } - - // implement avl tree insertion - const insert = function (root, val, tree) { - if (root == null) { - tree.size++ - return new Node(val) - } - if (tree._comp(root._val, val) < 0) { - root._right = insert(root._right, val, tree) - } else if (tree._comp(root._val, val) > 0) { - root._left = insert(root._left, val, tree) - } else { - return root - } - updateHeight(root) - const balanceFactor = getHeightDifference(root) - return isValidBalanceFactor(balanceFactor) - ? root - : insertBalance(root, val, balanceFactor, tree) - } - - // delete am element - const deleteElement = function (root, _val, tree) { - if (root == null) { - return root - } - if (tree._comp(root._val, _val) === 0) { - // key found case - if (root._left === null && root._right === null) { - root = null - tree.size-- - } else if (root._left === null) { - root = root._right - tree.size-- - } else if (root._right === null) { - root = root._left - tree.size-- - } else { - let temp = root._right - while (temp._left != null) { - temp = temp._left - } - root._val = temp._val - root._right = deleteElement(root._right, temp._val, tree) - } - } else { - if (tree._comp(root._val, _val) < 0) { - root._right = deleteElement(root._right, _val, tree) - } else { - root._left = deleteElement(root._left, _val, tree) - } - } - updateHeight(root) - root = delBalance(root) - return root - } - // search tree for a element - const searchAVLTree = function (root, val, tree) { - if (root == null) { - return null - } - if (tree._comp(root._val, val) === 0) { - return root - } - if (tree._comp(root._val, val) < 0) { - return searchAVLTree(root._right, val, tree) - } - return searchAVLTree(root._left, val, tree) - } - /* Public Functions */ /** * For Adding Elements to AVL Tree @@ -207,20 +51,22 @@ const AVLTree = (function () { * if a element exists it return false * @returns {Boolean} element added or not */ - _avl.prototype.add = function (_val) { + add(_val) { const prevSize = this.size this.root = insert(this.root, _val, this) return this.size !== prevSize } + /** * TO check is a particular element exists or not * @param {any} _val * @returns {Boolean} exists or not */ - _avl.prototype.find = function (_val) { + find(_val) { const temp = searchAVLTree(this.root, _val, this) return temp != null } + /** * * @param {any} _val @@ -228,13 +74,170 @@ const AVLTree = (function () { * in that case it return false * @returns {Boolean} if element was found and deleted */ - _avl.prototype.remove = function (_val) { + remove(_val) { const prevSize = this.size this.root = deleteElement(this.root, _val, this) return prevSize !== this.size } - return _avl -})() +} + +// creates new Node Object +class Node { + constructor(val) { + this._val = val + this._left = null + this._right = null + this._height = 1 + } +} + +// get height of a node +const getHeight = function (node) { + if (node == null) { + return 0 + } + return node._height +} + +// height difference or balance factor of a node +const getHeightDifference = function (node) { + return node == null ? 0 : getHeight(node._left) - getHeight(node._right) +} + +// update height of a node based on children's heights +const updateHeight = function (node) { + if (node == null) { + return + } + node._height = Math.max(getHeight(node._left), getHeight(node._right)) + 1 +} + +// Helper: To check if the balanceFactor is valid +const isValidBalanceFactor = (balanceFactor) => + [0, 1, -1].includes(balanceFactor) + +// rotations of AVL Tree +const leftRotate = function (node) { + const temp = node._right + node._right = temp._left + temp._left = node + updateHeight(node) + updateHeight(temp) + return temp +} +const rightRotate = function (node) { + const temp = node._left + node._left = temp._right + temp._right = node + updateHeight(node) + updateHeight(temp) + return temp +} + +// check if tree is balanced else balance it for insertion +const insertBalance = function (node, _val, balanceFactor, tree) { + if (balanceFactor > 1 && tree._comp(_val, node._left._val) < 0) { + return rightRotate(node) // Left Left Case + } + if (balanceFactor < 1 && tree._comp(_val, node._right._val) > 0) { + return leftRotate(node) // Right Right Case + } + if (balanceFactor > 1 && tree._comp(_val, node._left._val) > 0) { + node._left = leftRotate(node._left) // Left Right Case + return rightRotate(node) + } + node._right = rightRotate(node._right) + return leftRotate(node) +} + +// check if tree is balanced after deletion +const delBalance = function (node) { + const balanceFactor1 = getHeightDifference(node) + if (isValidBalanceFactor(balanceFactor1)) { + return node + } + if (balanceFactor1 > 1) { + if (getHeightDifference(node._left) >= 0) { + return rightRotate(node) // Left Left + } + node._left = leftRotate(node._left) + return rightRotate(node) // Left Right + } + if (getHeightDifference(node._right) > 0) { + node._right = rightRotate(node._right) + return leftRotate(node) // Right Left + } + return leftRotate(node) // Right Right +} + +// implement avl tree insertion +const insert = function (root, val, tree) { + if (root == null) { + tree.size++ + return new Node(val) + } + if (tree._comp(root._val, val) < 0) { + root._right = insert(root._right, val, tree) + } else if (tree._comp(root._val, val) > 0) { + root._left = insert(root._left, val, tree) + } else { + return root + } + updateHeight(root) + const balanceFactor = getHeightDifference(root) + return isValidBalanceFactor(balanceFactor) + ? root + : insertBalance(root, val, balanceFactor, tree) +} + +// delete am element +const deleteElement = function (root, _val, tree) { + if (root == null) { + return root + } + if (tree._comp(root._val, _val) === 0) { + // key found case + if (root._left === null && root._right === null) { + root = null + tree.size-- + } else if (root._left === null) { + root = root._right + tree.size-- + } else if (root._right === null) { + root = root._left + tree.size-- + } else { + let temp = root._right + while (temp._left != null) { + temp = temp._left + } + root._val = temp._val + root._right = deleteElement(root._right, temp._val, tree) + } + } else { + if (tree._comp(root._val, _val) < 0) { + root._right = deleteElement(root._right, _val, tree) + } else { + root._left = deleteElement(root._left, _val, tree) + } + } + updateHeight(root) + root = delBalance(root) + return root +} +// search tree for a element +const searchAVLTree = function (root, val, tree) { + if (root == null) { + return null + } + if (tree._comp(root._val, val) === 0) { + return root + } + if (tree._comp(root._val, val) < 0) { + return searchAVLTree(root._right, val, tree) + } + return searchAVLTree(root._left, val, tree) +} /** * A Code for Testing the AVLTree diff --git a/Data-Structures/Tree/BinarySearchTree.js b/Data-Structures/Tree/BinarySearchTree.js index c86a2995c0..abbcc3fb62 100644 --- a/Data-Structures/Tree/BinarySearchTree.js +++ b/Data-Structures/Tree/BinarySearchTree.js @@ -13,77 +13,79 @@ // class Node const Node = (function Node() { // Node in the tree - function Node(val) { - this.value = val - this.left = null - this.right = null - } - - // Search the tree for a value - Node.prototype.search = function (val) { - if (this.value === val) { - return this - } else if (val < this.value && this.left !== null) { - return this.left.search(val) - } else if (val > this.value && this.right !== null) { - return this.right.search(val) + class Node { + constructor(val) { + this.value = val + this.left = null + this.right = null } - return null - } - // Visit a node - Node.prototype.visit = function (output = (value) => console.log(value)) { - // Recursively go left - if (this.left !== null) { - this.left.visit() - } - // Print out value - output(this.value) - // Recursively go right - if (this.right !== null) { - this.right.visit() + // Search the tree for a value + search(val) { + if (this.value === val) { + return this + } else if (val < this.value && this.left !== null) { + return this.left.search(val) + } else if (val > this.value && this.right !== null) { + return this.right.search(val) + } + return null } - } - // Add a node - Node.prototype.addNode = function (n) { - if (n.value < this.value) { - if (this.left === null) { - this.left = n - } else { - this.left.addNode(n) + // Visit a node + visit(output = (value) => console.log(value)) { + // Recursively go left + if (this.left !== null) { + this.left.visit() } - } else if (n.value > this.value) { - if (this.right === null) { - this.right = n - } else { - this.right.addNode(n) + // Print out value + output(this.value) + // Recursively go right + if (this.right !== null) { + this.right.visit() } } - } - // remove a node - Node.prototype.removeNode = function (val) { - if (val === this.value) { - if (!this.left && !this.right) { - return null - } else { - if (this.left) { - const leftMax = maxVal(this.left) - this.value = leftMax - this.left = this.left.removeNode(leftMax) + // Add a node + addNode(n) { + if (n.value < this.value) { + if (this.left === null) { + this.left = n } else { - const rightMin = minVal(this.right) - this.value = rightMin - this.right = this.right.removeNode(rightMin) + this.left.addNode(n) + } + } else if (n.value > this.value) { + if (this.right === null) { + this.right = n + } else { + this.right.addNode(n) } } - } else if (val < this.value) { - this.left = this.left && this.left.removeNode(val) - } else if (val > this.value) { - this.right = this.right && this.right.removeNode(val) } - return this + + // remove a node + removeNode(val) { + if (val === this.value) { + if (!this.left && !this.right) { + return null + } else { + if (this.left) { + const leftMax = maxVal(this.left) + this.value = leftMax + this.left = this.left.removeNode(leftMax) + } else { + const rightMin = minVal(this.right) + this.value = rightMin + this.right = this.right.removeNode(rightMin) + } + } + } else if (val < this.value) { + this.left = this.left && this.left.removeNode(val) + } else if (val > this.value) { + this.right = this.right && this.right.removeNode(val) + } + return this + } } // find maximum value in the tree @@ -107,44 +109,46 @@ const Node = (function Node() { // class Tree const Tree = (function () { - function Tree() { - // Just store the root - this.root = null - } + class Tree { + constructor() { + // Just store the root + this.root = null + } - // Inorder traversal - Tree.prototype.traverse = function () { - if (!this.root) { - // No nodes are there in the tree till now - return + // Inorder traversal + traverse() { + if (!this.root) { + // No nodes are there in the tree till now + return + } + this.root.visit() } - this.root.visit() - } - // Start by searching the root - Tree.prototype.search = function (val) { - const found = this.root.search(val) - if (found !== null) { - return found.value + // Start by searching the root + search(val) { + const found = this.root.search(val) + if (found !== null) { + return found.value + } + // not found + return null } - // not found - return null - } - // Add a new value to the tree - Tree.prototype.addValue = function (val) { - const n = new Node(val) - if (this.root === null) { - this.root = n - } else { - this.root.addNode(n) + // Add a new value to the tree + addValue(val) { + const n = new Node(val) + if (this.root === null) { + this.root = n + } else { + this.root.addNode(n) + } } - } - // remove a value from the tree - Tree.prototype.removeValue = function (val) { - // remove something if root exists - this.root = this.root && this.root.removeNode(val) + // remove a value from the tree + removeValue(val) { + // remove something if root exists + this.root = this.root && this.root.removeNode(val) + } } // returns the constructor diff --git a/Data-Structures/Tree/Trie.js b/Data-Structures/Tree/Trie.js index ea59e53846..0d4018f74f 100644 --- a/Data-Structures/Tree/Trie.js +++ b/Data-Structures/Tree/Trie.js @@ -1,129 +1,132 @@ -const TrieNode = function TrieNode(key, parent) { - this.key = key - this.count = 0 - this.children = Object.create(null) - if (parent === undefined) { - this.parent = null - } else { - this.parent = parent +class TrieNode { + constructor(key, parent) { + this.key = key + this.count = 0 + this.children = Object.create(null) + if (parent === undefined) { + this.parent = null + } else { + this.parent = parent + } } } -function Trie() { - // create only root with null key and parent - this.root = new TrieNode(null, null) -} +class Trie { + constructor() { + // create only root with null key and parent + this.root = new TrieNode(null, null) + } -// Recursively finds the occurrence of all words in a given node -Trie.findAllWords = function (root, word, output) { - if (root === null) return - if (root.count > 0) { - if (typeof output === 'object') { - output.push({ word, count: root.count }) + // Recursively finds the occurrence of all words in a given node + static findAllWords(root, word, output) { + if (root === null) return + if (root.count > 0) { + if (typeof output === 'object') { + output.push({ word, count: root.count }) + } + } + let key + for (key in root.children) { + word += key + this.findAllWords(root.children[key], word, output) + word = word.slice(0, -1) } } - let key - for (key in root.children) { - word += key - this.findAllWords(root.children[key], word, output) - word = word.slice(0, -1) - } -} -Trie.prototype.insert = function (word) { - if (typeof word !== 'string') return - if (word === '') { - this.root.count += 1 - return - } - let node = this.root - const len = word.length - let i - for (i = 0; i < len; i++) { - if (node.children[word.charAt(i)] === undefined) { - node.children[word.charAt(i)] = new TrieNode(word.charAt(i), node) + insert(word) { + if (typeof word !== 'string') return + if (word === '') { + this.root.count += 1 + return + } + let node = this.root + const len = word.length + let i + for (i = 0; i < len; i++) { + if (node.children[word.charAt(i)] === undefined) { + node.children[word.charAt(i)] = new TrieNode(word.charAt(i), node) + } + node = node.children[word.charAt(i)] } - node = node.children[word.charAt(i)] + node.count += 1 } - node.count += 1 -} -Trie.prototype.findPrefix = function (word) { - if (typeof word !== 'string') return null - let node = this.root - const len = word.length - let i - // After end of this loop node will be at desired prefix - for (i = 0; i < len; i++) { - if (node.children[word.charAt(i)] === undefined) return null // No such prefix exists - node = node.children[word.charAt(i)] + findPrefix(word) { + if (typeof word !== 'string') return null + let node = this.root + const len = word.length + let i + // After end of this loop node will be at desired prefix + for (i = 0; i < len; i++) { + if (node.children[word.charAt(i)] === undefined) return null // No such prefix exists + node = node.children[word.charAt(i)] + } + return node } - return node -} -Trie.prototype.remove = function (word, count) { - if (typeof word !== 'string') return - if (typeof count !== 'number') count = 1 - else if (count <= 0) return + remove(word, count) { + if (typeof word !== 'string') return + if (typeof count !== 'number') count = 1 + else if (count <= 0) return - // for empty string just delete count of root - if (word === '') { - if (this.root.count >= count) this.root.count -= count - else this.root.count = 0 - return - } + // for empty string just delete count of root + if (word === '') { + if (this.root.count >= count) this.root.count -= count + else this.root.count = 0 + return + } - let child = this.root - const len = word.length - let i, key - // child: node which is to be deleted - for (i = 0; i < len; i++) { - key = word.charAt(i) - if (child.children[key] === undefined) return - child = child.children[key] - } + let child = this.root + const len = word.length + let i, key + // child: node which is to be deleted + for (i = 0; i < len; i++) { + key = word.charAt(i) + if (child.children[key] === undefined) return + child = child.children[key] + } - // Delete no of occurrences specified - if (child.count >= count) child.count -= count - else child.count = 0 + // Delete no of occurrences specified + if (child.count >= count) child.count -= count + else child.count = 0 - // If some occurrences are left we don't delete it or else - // if the object forms some other objects prefix we don't delete it - // For checking an empty object - // https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object - if ( - child.count <= 0 && - Object.keys(child.children).length && - child.children.constructor === Object - ) { - child.parent.children[child.key] = undefined + // If some occurrences are left we don't delete it or else + // if the object forms some other objects prefix we don't delete it + // For checking an empty object + // https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object + if ( + child.count <= 0 && + Object.keys(child.children).length && + child.children.constructor === Object + ) { + child.parent.children[child.key] = undefined + } } -} -Trie.prototype.findAllWords = function (prefix) { - const output = [] - // find the node with provided prefix - const node = this.findPrefix(prefix) - // No such prefix exists - if (node === null) return output - Trie.findAllWords(node, prefix, output) - return output -} - -Trie.prototype.contains = function (word) { - // find the node with given prefix - const node = this.findPrefix(word) - // No such word exists + findAllWords(prefix) { + const output = [] + // find the node with provided prefix + const node = this.findPrefix(prefix) + // No such prefix exists + if (node === null) return output + Trie.findAllWords(node, prefix, output) + return output + } - return node !== null && node.count !== 0 -} + contains(word) { + // find the node with given prefix + const node = this.findPrefix(word) + // No such word exists + return node !== null && node.count !== 0 + } -Trie.prototype.findOccurrences = function (word) { - // find the node with given prefix - const node = this.findPrefix(word) - // No such word exists - if (node === null) return 0 - return node.count + findOccurrences(word) { + // find the node with given prefix + const node = this.findPrefix(word) + // No such word exists + if (node === null) return 0 + return node.count + } } export { Trie } diff --git a/Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js b/Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js index dee12f8de9..48905c39e2 100644 --- a/Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js +++ b/Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js @@ -4,7 +4,7 @@ determine the total number of the subset with sum equal to the given sum. */ /* - Given solution is O(n*sum) Time complexity and O(sum) Space complexity + Given solution is O(n*sum) Time complexity and O(sum) Space complexity */ function NumberOfSubsetSum(array, sum) { const dp = [] // create an dp array where dp[i] denote number of subset with sum equal to i diff --git a/Hashes/tests/SHA1.test.js b/Hashes/tests/SHA1.test.js new file mode 100644 index 0000000000..8032e29908 --- /dev/null +++ b/Hashes/tests/SHA1.test.js @@ -0,0 +1,25 @@ +import { describe, test } from 'vitest' +import { SHA1 } from '../SHA1' + +describe('Testing SHA1 function', () => { + it.each([ + ['', 'da39a3ee5e6b4b0d3255bfef95601890afd80709'], + [ + 'The quick brown fox jumps over the lazy dog', + '2fd4e1c67a2d28fced849ee1bb76e7391b93eb12' + ], + [ + 'The quick brown fox jumps over the lazy cog', + 'de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3' + ], + ['a', '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8'], + ['Today is 29.01.2024!', 'ae829b60d11fb5ab527d5db2501e06da3402718d'], + ['Have a nice day.', 'ed51dd3909281c25db5e1d8b1ce6fc701fda20ab'], + [ + '12345678901234567890123456789012345678901234567890123456789012345678901234567890', + '50abf5706a150990a08b2c5ea40fa0e585554732' + ] + ])('check with %j', (input, expected) => { + expect(SHA1(input)).toBe(expected) + }) +}) diff --git a/Hashes/tests/SHA256.test.js b/Hashes/tests/SHA256.test.js new file mode 100644 index 0000000000..1ffb236cea --- /dev/null +++ b/Hashes/tests/SHA256.test.js @@ -0,0 +1,27 @@ +import { describe, test } from 'vitest' +import { SHA256 } from '../SHA256' + +describe('Testing SHA256 function', () => { + it.each([ + ['', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'], + [ + 'The quick brown fox jumps over the lazy dog', + 'd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592' + ], + [ + 'The quick brown fox jumps over the lazy cog', + 'e4c4d8f3bf76b692de791a173e05321150f7a345b46484fe427f6acc7ecc81be' + ], + [ + 'This was added by vil02 on 01.02.2024. Have a nice day!', + '476025d91db754ab6ac0c124367afd7c108d041b2f497006a214d5035769ed5d' + ], + [ + '012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789', + '14582b3f153941891dca966b036a5b1de65fa3b7a2540095a31614da1de0feaf' + ], + ['a', 'ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb'] + ])('check with %j', (input, expected) => { + expect(SHA256(input)).toBe(expected) + }) +}) diff --git a/Maths/BisectionMethod.js b/Maths/BisectionMethod.js index 49b8c8ecc0..4539e6d466 100644 --- a/Maths/BisectionMethod.js +++ b/Maths/BisectionMethod.js @@ -23,7 +23,7 @@ const findRoot = (a, b, func, numberOfIterations) => { // Bolzano theorem const hasRoot = (a, b, func) => { - return func(a) * func(b) < 0 + return func(a) * func(b) <= 0 } if (hasRoot(a, b, func) === false) { throw Error( @@ -45,10 +45,9 @@ const findRoot = (a, b, func, numberOfIterations) => { const prod2 = fm * func(b) // Depending on the sign of the products above, decide which position will m fill (a's or b's) - if (prod1 > 0 && prod2 < 0) return findRoot(m, b, func, --numberOfIterations) - else if (prod1 < 0 && prod2 > 0) - return findRoot(a, m, func, --numberOfIterations) - else throw Error('Unexpected behavior') + if (prod2 <= 0) return findRoot(m, b, func, --numberOfIterations) + + return findRoot(a, m, func, --numberOfIterations) } export { findRoot } diff --git a/Maths/CheckKishnamurthyNumber.js b/Maths/CheckKishnamurthyNumber.js index 7a0cc9a0cc..5098b0fa7f 100644 --- a/Maths/CheckKishnamurthyNumber.js +++ b/Maths/CheckKishnamurthyNumber.js @@ -24,7 +24,10 @@ const factorial = (n) => { const CheckKishnamurthyNumber = (number) => { // firstly, check that input is a number or not. if (typeof number !== 'number') { - return new TypeError('Argument is not a number.') + throw new TypeError('Argument is not a number.') + } + if (number === 0) { + return false } // create a variable to store the sum of all digits factorial. let sumOfAllDigitFactorial = 0 diff --git a/Maths/CoPrimeCheck.js b/Maths/CoPrimeCheck.js index 3d9a0a3993..6f0437eaac 100644 --- a/Maths/CoPrimeCheck.js +++ b/Maths/CoPrimeCheck.js @@ -9,14 +9,7 @@ is coprime with b. */ -// Here we use a GetEuclidGCD method as a utility. -const GetEuclidGCD = (arg1, arg2) => { - let less = arg1 > arg2 ? arg2 : arg1 - for (less; less >= 2; less--) { - if (arg1 % less === 0 && arg2 % less === 0) return less - } - return less -} +import { GetEuclidGCD } from './GetEuclidGCD' // CoPrimeCheck function return the boolean in respect of the given number is co-prime or not. /** @@ -26,10 +19,6 @@ const GetEuclidGCD = (arg1, arg2) => { * @returns return correspond boolean value, if both number are co-prime return `true`, else return `false`. */ const CoPrimeCheck = (firstNumber, secondNumber) => { - // firstly, check that input is a number or not. - if (typeof firstNumber !== 'number' || typeof secondNumber !== 'number') { - return new TypeError('Argument is not a number.') - } /* This is the most efficient algorithm for checking co-primes if the GCD of both the numbers is 1 that means they are co-primes. diff --git a/Maths/GetEuclidGCD.js b/Maths/GetEuclidGCD.js index 5499057d78..42a30a6042 100644 --- a/Maths/GetEuclidGCD.js +++ b/Maths/GetEuclidGCD.js @@ -1,3 +1,9 @@ +function CheckInput(a, b) { + if (typeof a !== 'number' || typeof b !== 'number') { + throw new TypeError('Arguments must be numbers') + } +} + /** * GetEuclidGCD Euclidean algorithm to determine the GCD of two numbers * @param {Number} a integer (may be negative) @@ -5,10 +11,7 @@ * @returns {Number} Greatest Common Divisor gcd(a, b) */ export function GetEuclidGCD(a, b) { - if (typeof a !== 'number' || typeof b !== 'number') { - throw new TypeError('Arguments must be numbers') - } - if (a === 0 && b === 0) return undefined // infinitely many numbers divide 0 + CheckInput(a, b) a = Math.abs(a) b = Math.abs(b) while (b !== 0) { @@ -18,3 +21,19 @@ export function GetEuclidGCD(a, b) { } return a } + +/** + * Recursive version of GetEuclidGCD + * @param {Number} a integer (may be negative) + * @param {Number} b integer (may be negative) + * @returns {Number} Greatest Common Divisor gcd(a, b) + */ +export function GetEuclidGCDRecursive(a, b) { + CheckInput(a, b) + a = Math.abs(a) + b = Math.abs(b) + if (b == 0) { + return a + } + return GetEuclidGCDRecursive(b, a % b) +} diff --git a/Maths/PascalTriangle.js b/Maths/PascalTriangle.js index 868e36fcac..71d782cd61 100644 --- a/Maths/PascalTriangle.js +++ b/Maths/PascalTriangle.js @@ -17,8 +17,6 @@ const generate = (numRows) => { return [] } else if (numRows === 1) { return [[1]] - } else if (numRows === 2) { - return [[1], [1, 1]] } else { for (let i = 2; i < numRows; i++) { addRow(triangle) diff --git a/Maths/ReverseNumber.js b/Maths/ReverseNumber.js index 2f29903c93..4874cb3a86 100644 --- a/Maths/ReverseNumber.js +++ b/Maths/ReverseNumber.js @@ -10,7 +10,7 @@ const ReverseNumber = (number) => { // firstly, check that input is a number or not. if (typeof number !== 'number') { - return new TypeError('Argument is not a number.') + throw new TypeError('Argument is not a number.') } // A variable for storing the reversed number. let reverseNumber = 0 diff --git a/Maths/TwinPrime.js b/Maths/TwinPrime.js deleted file mode 100644 index 0bb17e0ebe..0000000000 --- a/Maths/TwinPrime.js +++ /dev/null @@ -1,29 +0,0 @@ -import { PrimeCheck } from './PrimeCheck' - -/** - * @function twinPrime - * Gets the 'twin prime' of a prime number. - * - * @param {Integer} n The number to find the twin prime of. - * @returns {Integer} Either the twin, or -1 if n or n + 2 is not prime. - * - * @see https://en.wikipedia.org/wiki/Twin_prime - * - * @example twinPrime(5) = 7 - * @example twinPrime(4) = -1 - */ -function twinPrime(n) { - const prime = PrimeCheck(n) - - if (!prime) { - return -1 - } - - if (!PrimeCheck(n + 2)) { - return -1 - } - - return n + 2 -} - -export { twinPrime } diff --git a/Maths/test/BisectionMethod.test.js b/Maths/test/BisectionMethod.test.js index ad865b6ad6..4a49e8f6a4 100644 --- a/Maths/test/BisectionMethod.test.js +++ b/Maths/test/BisectionMethod.test.js @@ -1,14 +1,7 @@ import { findRoot } from '../BisectionMethod' test('Equation f(x) = x^2 - 3*x + 2 = 0, has root x = 1 in [a, b] = [0, 1.5]', () => { - const root = findRoot( - 0, - 1.5, - (x) => { - return Math.pow(x, 2) - 3 * x + 2 - }, - 8 - ) + const root = findRoot(0, 1.5, (x) => x ** 2 - 3 * x + 2, 8) expect(root).toBe(0.9990234375) }) @@ -35,3 +28,12 @@ test('Equation f(x) = sqrt(x) + e^(2*x) - 8*x = 0, has root x = 0.93945851 in [a ) expect(Number(Number(root).toPrecision(8))).toBe(0.93945851) }) + +test('Equation f(x) = x^3 = 0, has root x = 0.0 in [a, b] = [-1.0, 1.0]', () => { + const root = findRoot(-1.0, 1.0, (x) => x ** 3, 32) + expect(root).toBeCloseTo(0.0, 5) +}) + +test('Throws an error when function does not change sign', () => { + expect(() => findRoot(-1.0, 1.0, (x) => x ** 2, 10)).toThrowError() +}) diff --git a/Maths/test/CheckKishnamurthyNumber.test.js b/Maths/test/CheckKishnamurthyNumber.test.js new file mode 100644 index 0000000000..4f2e0db952 --- /dev/null +++ b/Maths/test/CheckKishnamurthyNumber.test.js @@ -0,0 +1,18 @@ +import { CheckKishnamurthyNumber } from '../CheckKishnamurthyNumber' + +describe('CheckKishnamurthyNumber', () => { + it.each([1, 2, 145, 40585])('returns true for %i', (num) => { + expect(CheckKishnamurthyNumber(num)).toBe(true) + }) + + it.each([0, 3, 4, 5, 100, 146, 1019823, -1])( + 'returns false for %i', + (num) => { + expect(CheckKishnamurthyNumber(num)).toBe(false) + } + ) + + it('should throw when input is not a number', () => { + expect(() => CheckKishnamurthyNumber('2')).toThrowError() + }) +}) diff --git a/Maths/test/CoPrimeCheck.test.js b/Maths/test/CoPrimeCheck.test.js new file mode 100644 index 0000000000..7a46bcf6cf --- /dev/null +++ b/Maths/test/CoPrimeCheck.test.js @@ -0,0 +1,33 @@ +import { CoPrimeCheck } from '../CoPrimeCheck' + +describe('CoPrimeCheck', () => { + it.each([ + [1, 1], + [1, 2], + [1, 3], + [1, 7], + [20, 21], + [5, 7], + [-5, -7], + [1, 0], + [-1, 0] + ])('returns true for %j and %i', (inputA, inputB) => { + expect(CoPrimeCheck(inputA, inputB)).toBe(true) + expect(CoPrimeCheck(inputB, inputA)).toBe(true) + }) + + it.each([ + [5, 15], + [13 * 17 * 19, 17 * 23 * 29], + [2, 0], + [0, 0] + ])('returns false for %j and %i', (inputA, inputB) => { + expect(CoPrimeCheck(inputA, inputB)).toBe(false) + expect(CoPrimeCheck(inputB, inputA)).toBe(false) + }) + + it('should throw when any of the inputs is not a number', () => { + expect(() => CoPrimeCheck('1', 2)).toThrowError() + expect(() => CoPrimeCheck(1, '2')).toThrowError() + }) +}) diff --git a/Maths/test/GetEuclidGCD.test.js b/Maths/test/GetEuclidGCD.test.js index 1639d9cb7f..92f888acea 100644 --- a/Maths/test/GetEuclidGCD.test.js +++ b/Maths/test/GetEuclidGCD.test.js @@ -1,12 +1,22 @@ -import { GetEuclidGCD } from '../GetEuclidGCD' +import { GetEuclidGCD, GetEuclidGCDRecursive } from '../GetEuclidGCD' -function testEuclidGCD(n, m, expected) { - test('Testing on ' + n + ' and ' + m + '!', () => { - expect(GetEuclidGCD(n, m)).toBe(expected) +describe.each([GetEuclidGCD, GetEuclidGCDRecursive])('%o', (gcdFunction) => { + it.each([ + [5, 20, 5], + [109, 902, 1], + [290, 780, 10], + [104, 156, 52], + [0, 100, 100], + [-5, 50, 5], + [0, 0, 0], + [1, 1234567, 1] + ])('returns correct result for %i and %j', (inputA, inputB, expected) => { + expect(gcdFunction(inputA, inputB)).toBe(expected) + expect(gcdFunction(inputB, inputA)).toBe(expected) }) -} -testEuclidGCD(5, 20, 5) -testEuclidGCD(109, 902, 1) -testEuclidGCD(290, 780, 10) -testEuclidGCD(104, 156, 52) + it('should throw when any of the inputs is not a number', () => { + expect(() => gcdFunction('1', 2)).toThrowError() + expect(() => gcdFunction(1, '2')).toThrowError() + }) +}) diff --git a/Maths/test/PascalTriangle.test.js b/Maths/test/PascalTriangle.test.js index 314d0f3211..65c736f14f 100644 --- a/Maths/test/PascalTriangle.test.js +++ b/Maths/test/PascalTriangle.test.js @@ -1,20 +1,20 @@ +import { expect } from 'vitest' import { generate } from '../PascalTriangle' describe('Pascals Triangle', () => { - it('should have the the same length as the number', () => { - const pascalsTriangle = generate(5) - expect(pascalsTriangle.length).toEqual(5) - }) - it('should have same length as its index in the array', () => { - const pascalsTriangle = generate(5) + it.each([ + [0, []], + [1, [[1]]], + [2, [[1], [1, 1]]], + [3, [[1], [1, 1], [1, 2, 1]]], + [4, [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]], + [5, [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]], [1, 4, 6, 4, 1]] + ])('check with %j', (input, expected) => { + const pascalsTriangle = generate(input) + expect(pascalsTriangle.length).toEqual(input) pascalsTriangle.forEach((arr, index) => { expect(arr.length).toEqual(index + 1) }) - }) - it('should return an array of arrays', () => { - const pascalsTriangle = generate(3) - expect(pascalsTriangle).toEqual( - expect.arrayContaining([[1], [1, 1], [1, 2, 1]]) - ) + expect(pascalsTriangle).toEqual(expect.arrayContaining(expected)) }) }) diff --git a/Maths/test/ReverseNumber.test.js b/Maths/test/ReverseNumber.test.js new file mode 100644 index 0000000000..64593cbe14 --- /dev/null +++ b/Maths/test/ReverseNumber.test.js @@ -0,0 +1,16 @@ +import { ReverseNumber } from '../ReverseNumber' + +describe('ReverseNumber', () => { + it.each([ + [0, 0], + [10, 1], + [123, 321], + [100001, 100001] + ])('check with %j', (input, expected) => { + expect(expected).toEqual(ReverseNumber(input)) + }) + + it('should throw when input is not a number', () => { + expect(() => ReverseNumber('100')).toThrowError() + }) +}) diff --git a/Maths/test/SumOfGeometricProgression.test.js b/Maths/test/SumOfGeometricProgression.test.js index f459835232..0edf2b9f8e 100644 --- a/Maths/test/SumOfGeometricProgression.test.js +++ b/Maths/test/SumOfGeometricProgression.test.js @@ -8,4 +8,8 @@ describe('Sum Of Geometric Progression', () => { it('should return the sum of an infinite GP', () => { expect(sumOfGeometricProgression(2, 0.5, Infinity)).toBe(4) }) + + it('should throw when series diverges', () => { + expect(() => sumOfGeometricProgression(1, 1, Infinity)).toThrowError() + }) }) diff --git a/Maths/test/TwinPrime.test.js b/Maths/test/TwinPrime.test.js deleted file mode 100644 index c3e057e10e..0000000000 --- a/Maths/test/TwinPrime.test.js +++ /dev/null @@ -1,10 +0,0 @@ -import { twinPrime } from '../TwinPrime.js' - -describe('Twin Primes', () => { - it('Should be valid twin primes', () => { - expect(twinPrime(3)).toBe(5) - expect(twinPrime(5)).toBe(7) - expect(twinPrime(4)).toBe(-1) - expect(twinPrime(17)).toBe(19) - }) -}) diff --git a/Project-Euler/Problem004.js b/Project-Euler/Problem004.js index 34fa87471d..7c85dfdb85 100644 --- a/Project-Euler/Problem004.js +++ b/Project-Euler/Problem004.js @@ -1,6 +1,6 @@ // https://projecteuler.net/problem=4 /* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. - Find the largest palindrome made from the product of two 3-digit numbers. + Find the largest palindrome made from the product of two 3-digit numbers. */ export const largestPalindromic = (digits) => { let i diff --git a/README.md b/README.md index 65dfb501df..bd9582fe94 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ JavaScript Repository of TheAlgorithms, which implements various algorithms and [![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/JavaScript) [![Checks][checks]][actions] +[![codecov](https://codecov.io/gh/TheAlgorithms/JavaScript/graph/badge.svg?token=8VeZwL31KZ)](https://codecov.io/gh/TheAlgorithms/JavaScript) [![Contributions Welcome][welcome]](CONTRIBUTING.md) [![standard.js][standard-logo]][standard-js] [![Discord chat][chat]][discord-server] diff --git a/Recursive/EucledianGCD.js b/Recursive/EucledianGCD.js deleted file mode 100644 index e0cc15ed56..0000000000 --- a/Recursive/EucledianGCD.js +++ /dev/null @@ -1,30 +0,0 @@ -function euclideanGCDRecursive(first, second) { - /* - Calculates GCD of two numbers using Euclidean Recursive Algorithm - :param first: First number - :param second: Second number - :return: GCD of the numbers - */ - if (second === 0) { - return first - } else { - return euclideanGCDRecursive(second, first % second) - } -} - -function euclideanGCDIterative(first, second) { - /* - Calculates GCD of two numbers using Euclidean Iterative Algorithm - :param first: First number - :param second: Second number - :return: GCD of the numbers - */ - while (second !== 0) { - const temp = second - second = first % second - first = temp - } - return first -} - -export { euclideanGCDIterative, euclideanGCDRecursive } diff --git a/Recursive/FloodFill.js b/Recursive/FloodFill.js index 33ea6025ad..5143b8f4ff 100644 --- a/Recursive/FloodFill.js +++ b/Recursive/FloodFill.js @@ -9,7 +9,7 @@ * @see https://www.techiedelight.com/flood-fill-algorithm/ */ -const neighbors = [ +const neighborOffsets = [ [-1, -1], [-1, 0], [-1, 1], @@ -20,6 +20,27 @@ const neighbors = [ [1, 1] ] +function isInside(rgbData, location) { + const x = location[0] + const y = location[1] + return x >= 0 && x < rgbData.length && y >= 0 && y < rgbData[0].length +} + +function checkLocation(rgbData, location) { + if (!isInside(rgbData, location)) { + throw new Error('location should point to a pixel within the rgbData') + } +} + +function* neighbors(rgbData, location) { + for (const offset of neighborOffsets) { + const neighborLocation = [location[0] + offset[0], location[1] + offset[1]] + if (isInside(rgbData, neighborLocation)) { + yield neighborLocation + } + } +} + /** * Implements the flood fill algorithm through a breadth-first approach using a queue. * @@ -34,14 +55,7 @@ export function breadthFirstSearch( targetColor, replacementColor ) { - if ( - location[0] < 0 || - location[0] >= rgbData.length || - location[1] < 0 || - location[1] >= rgbData[0].length - ) { - throw new Error('location should point to a pixel within the rgbData') - } + checkLocation(rgbData, location) const queue = [] queue.push(location) @@ -65,14 +79,7 @@ export function depthFirstSearch( targetColor, replacementColor ) { - if ( - location[0] < 0 || - location[0] >= rgbData.length || - location[1] < 0 || - location[1] >= rgbData[0].length - ) { - throw new Error('location should point to a pixel within the rgbData') - } + checkLocation(rgbData, location) depthFirstFill(rgbData, location, targetColor, replacementColor) } @@ -98,13 +105,8 @@ function breadthFirstFill( if (rgbData[currentLocation[0]][currentLocation[1]] === targetColor) { rgbData[currentLocation[0]][currentLocation[1]] = replacementColor - - for (let i = 0; i < neighbors.length; i++) { - const x = currentLocation[0] + neighbors[i][0] - const y = currentLocation[1] + neighbors[i][1] - if (x >= 0 && x < rgbData.length && y >= 0 && y < rgbData[0].length) { - queue.push([x, y]) - } + for (const neighborLocation of neighbors(rgbData, currentLocation)) { + queue.push(neighborLocation) } } } @@ -120,13 +122,8 @@ function breadthFirstFill( function depthFirstFill(rgbData, location, targetColor, replacementColor) { if (rgbData[location[0]][location[1]] === targetColor) { rgbData[location[0]][location[1]] = replacementColor - - for (let i = 0; i < neighbors.length; i++) { - const x = location[0] + neighbors[i][0] - const y = location[1] + neighbors[i][1] - if (x >= 0 && x < rgbData.length && y >= 0 && y < rgbData[0].length) { - depthFirstFill(rgbData, [x, y], targetColor, replacementColor) - } + for (const neighborLocation of neighbors(rgbData, location)) { + depthFirstFill(rgbData, neighborLocation, targetColor, replacementColor) } } } diff --git a/Recursive/test/FloodFill.test.js b/Recursive/test/FloodFill.test.js index 291788addd..618692dd97 100644 --- a/Recursive/test/FloodFill.test.js +++ b/Recursive/test/FloodFill.test.js @@ -21,6 +21,19 @@ describe('FloodFill', () => { }) }) +describe.each([breadthFirstSearch, depthFirstSearch])('%o', (floodFillFun) => { + it.each([ + [1, -1], + [-1, 1], + [0, 7], + [7, 0] + ])('throws for start position [%i, %i]', (location) => { + expect(() => + floodFillFun(generateTestRgbData(), location, green, orange) + ).toThrowError() + }) +}) + /** * Utility-function to test the function "breadthFirstSearch". * diff --git a/String/CheckFlatCase.js b/String/CheckFlatCase.js index 709825edd1..5f8a332999 100644 --- a/String/CheckFlatCase.js +++ b/String/CheckFlatCase.js @@ -12,7 +12,7 @@ const checkFlatCase = (varname) => { // firstly, check that input is a string or not. if (typeof varname !== 'string') { - return new TypeError('Argument is not a string.') + throw new TypeError('Argument is not a string.') } const pat = /^[a-z]*$/ diff --git a/String/CheckKebabCase.js b/String/CheckKebabCase.js index 6e79ba6a5e..52d322f921 100644 --- a/String/CheckKebabCase.js +++ b/String/CheckKebabCase.js @@ -10,7 +10,7 @@ const CheckKebabCase = (varName) => { // firstly, check that input is a string or not. if (typeof varName !== 'string') { - return new TypeError('Argument is not a string.') + throw new TypeError('Argument is not a string.') } const pat = /(\w+)-(\w)([\w-]*)/ diff --git a/String/CheckPascalCase.js b/String/CheckPascalCase.js index 2e4c1ff3fa..71aaa26770 100644 --- a/String/CheckPascalCase.js +++ b/String/CheckPascalCase.js @@ -10,7 +10,7 @@ const CheckPascalCase = (VarName) => { // firstly, check that input is a string or not. if (typeof VarName !== 'string') { - return new TypeError('Argument is not a string.') + throw new TypeError('Argument is not a string.') } const pat = /^[A-Z][A-Za-z]*$/ diff --git a/String/test/CheckCamelCase.test.js b/String/test/CheckCamelCase.test.js index c1e2d83005..5875e0cd10 100644 --- a/String/test/CheckCamelCase.test.js +++ b/String/test/CheckCamelCase.test.js @@ -15,4 +15,8 @@ describe('checkCamelCase', () => { const result = checkCamelCase(value) expect(result).toBe(false) }) + + it('should throw when input is not a string', () => { + expect(() => checkCamelCase(100)).toThrowError() + }) }) diff --git a/String/test/CheckFlatCase.test.js b/String/test/CheckFlatCase.test.js index 0277f7c0e1..ccac811bf6 100644 --- a/String/test/CheckFlatCase.test.js +++ b/String/test/CheckFlatCase.test.js @@ -15,4 +15,8 @@ describe('checkFlatCase function', () => { const actual = checkFlatCase('abcdefghijklmnopqrstuvwxyz') expect(actual).toBe(true) }) + + it('should throw when input is not a string', () => { + expect(() => checkFlatCase(100)).toThrowError() + }) }) diff --git a/String/test/CheckKebabCase.test.js b/String/test/CheckKebabCase.test.js index 45bc5f2d52..239d91674e 100644 --- a/String/test/CheckKebabCase.test.js +++ b/String/test/CheckKebabCase.test.js @@ -11,3 +11,7 @@ test('CheckKebabCase(The Algorithms) -> false', () => { const res = CheckKebabCase(word) expect(res).toBeFalsy() }) + +test('CheckKebabCase throws when input is not a string', () => { + expect(() => CheckKebabCase(100)).toThrowError() +}) diff --git a/String/test/CheckPascalCase.test.js b/String/test/CheckPascalCase.test.js index 2587023f79..139b66844b 100644 --- a/String/test/CheckPascalCase.test.js +++ b/String/test/CheckPascalCase.test.js @@ -17,3 +17,7 @@ test('CheckPascalCase(The Algorithms) -> false', () => { const res = CheckPascalCase(word) expect(res).toBeFalsy() }) + +test('CheckPascalCase throws when input is not a string', () => { + expect(() => CheckPascalCase(100)).toThrowError() +}) diff --git a/Timing-Functions/GetMonthDays.js b/Timing-Functions/GetMonthDays.js index ce188c9603..43c2e7e6e6 100644 --- a/Timing-Functions/GetMonthDays.js +++ b/Timing-Functions/GetMonthDays.js @@ -6,6 +6,8 @@ e.g.: mahfoudh.arous.com ->false */ +import { isLeapYear } from '../Maths/LeapYear' + const getMonthDays = (monthNumber, year) => { const the31DaysMonths = [1, 3, 5, 7, 8, 10, 12] const the30DaysMonths = [4, 6, 9, 11] @@ -26,11 +28,8 @@ const getMonthDays = (monthNumber, year) => { return 30 } - // Check for Leap year - if (year % 4 === 0) { - if (year % 100 !== 0 || (year % 100 === 0 && year % 400 === 0)) { - return 29 - } + if (isLeapYear(year)) { + return 29 } return 28 diff --git a/Timing-Functions/ParseDate.js b/Timing-Functions/ParseDate.js new file mode 100644 index 0000000000..67f4e4cd0e --- /dev/null +++ b/Timing-Functions/ParseDate.js @@ -0,0 +1,27 @@ +import { getMonthDays } from './GetMonthDays' + +function checkDate(date) { + if (date.day < 1 || date.day > getMonthDays(date.month, date.year)) { + throw new Error('Invalid day value.') + } +} + +function parseDate(dateString) { + const regex = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/ + + const match = dateString.match(regex) + + if (!match) { + throw new Error("Invalid date format. Please use 'dd/mm/yyyy'.") + } + + const res = { + day: parseInt(match[1], 10), + month: parseInt(match[2], 10), + year: parseInt(match[3], 10) + } + checkDate(res) + return res +} + +export { parseDate } diff --git a/Timing-Functions/test/GetMonthDays.test.js b/Timing-Functions/test/GetMonthDays.test.js index b7527c0ac6..1222cc4ae0 100644 --- a/Timing-Functions/test/GetMonthDays.test.js +++ b/Timing-Functions/test/GetMonthDays.test.js @@ -1,16 +1,33 @@ import { getMonthDays } from '../GetMonthDays' describe('Get the Days of a Month', () => { - it('expects to return 28', () => { - expect(getMonthDays(2, 2018)).toEqual(28) - }) - - it('expects to return 30', () => { - expect(getMonthDays(6, 254)).toEqual(30) - }) - - it('expects to return 29', () => { - expect(getMonthDays(2, 2024)).toEqual(29) + it.each([ + [1, 2024, 31], + [2, 2024, 29], + [3, 2024, 31], + [4, 2024, 30], + [5, 2024, 31], + [6, 2024, 30], + [7, 2024, 31], + [8, 2024, 31], + [9, 2024, 30], + [10, 2024, 31], + [11, 2024, 30], + [12, 2024, 31], + [1, 2023, 31], + [2, 2023, 28], + [3, 2023, 31], + [4, 2023, 30], + [5, 2023, 31], + [6, 2023, 30], + [7, 2023, 31], + [8, 2023, 31], + [9, 2023, 30], + [10, 2023, 31], + [11, 2023, 30], + [12, 2023, 31] + ])('Month %i in year %i has %i days', (month, year, expected) => { + expect(getMonthDays(month, year)).toBe(expected) }) it('expects to throw a type error', () => { diff --git a/Timing-Functions/test/ParseDate.test.js b/Timing-Functions/test/ParseDate.test.js new file mode 100644 index 0000000000..3b807bb8a5 --- /dev/null +++ b/Timing-Functions/test/ParseDate.test.js @@ -0,0 +1,40 @@ +import { parseDate } from '../ParseDate' + +describe('parseDate', () => { + it.each([ + ['18/03/2024', { year: 2024, month: 3, day: 18 }], + ['29/02/2024', { year: 2024, month: 2, day: 29 }], + ['28/02/2023', { year: 2023, month: 2, day: 28 }], + ['01/12/2024', { year: 2024, month: 12, day: 1 }], + ['1/12/2024', { year: 2024, month: 12, day: 1 }], + ['10/1/2024', { year: 2024, month: 1, day: 10 }] + ])('Returns correct output for %s', (dateString, expected) => { + expect(parseDate(dateString)).toStrictEqual(expected) + }) + + it.each([ + '18-03-2024', + '18.03.2024', + '03/2024', + '01/02/03/2024', + '123/03/2024' + ])('Throws for %s', (wrongDateString) => { + expect(() => { + parseDate(wrongDateString) + }).toThrow() + }) + + it.each([ + '40/03/2024', + '30/02/2024', + '29/02/2023', + '31/04/2023', + '00/01/2024', + '01/00/2024', + '01/13/2024' + ])('Throws for %s', (wrongDateString) => { + expect(() => { + parseDate(wrongDateString) + }).toThrow() + }) +}) diff --git a/Trees/DepthFirstSearch.js b/Trees/DepthFirstSearch.js index 7c67afc95e..f4ce2cfed5 100644 --- a/Trees/DepthFirstSearch.js +++ b/Trees/DepthFirstSearch.js @@ -44,30 +44,4 @@ function searchDFS(tree, value) { return null } -const tree = [ - { value: 6, left: 1, right: 2 }, - { value: 5, left: 3, right: 4 }, - { value: 7, left: null, right: 5 }, - { value: 3, left: 6, right: null }, - { value: 4, left: null, right: null }, - { value: 9, left: 7, right: 8 }, - { value: 2, left: 9, right: null }, - { value: 8, left: null, right: null }, - { value: 10, left: null, right: null }, - { value: 1, left: null, right: null } -] -searchDFS(tree, 9) // { value: 9, left: 7, right: 8 } -searchDFS(tree, 200) // null -traverseDFS(tree, 6) // [ 1, 2, 3, 4, 5, 8, 10, 9, 7, 6 ] -traverseDFS(tree, 200) // [] - -// 6 -// / \ -// 5 7 -// / \ \ -// 3 4 9 -// / / \ -// 2 8 10 -// / -// 1 export { searchDFS, traverseDFS }