diff --git a/Backtracking/AllCombinationsOfSizeK.js b/Backtracking/AllCombinationsOfSizeK.js index 61a1d55c38..547a38c303 100644 --- a/Backtracking/AllCombinationsOfSizeK.js +++ b/Backtracking/AllCombinationsOfSizeK.js @@ -25,19 +25,21 @@ class Combinations { constructor (n, k) { this.n = n this.k = k - this.combinationArray = [] // will be used for storing current combination + this.current = [] // will be used for storing current combination + this.combinations = [] } findCombinations (high = this.n, total = this.k, low = 1) { if (total === 0) { - console.log(this.combinationArray) - return + this.combinations.push([...this.current]) + return this.combinations } for (let i = low; i <= high; i++) { - this.combinationArray.push(i) + this.current.push(i) this.findCombinations(high, total - 1, i + 1) - this.combinationArray.pop() + this.current.pop() } + return this.combinations } } diff --git a/Backtracking/GeneratePermutations.js b/Backtracking/GeneratePermutations.js index fa302345d7..1629e2aa84 100644 --- a/Backtracking/GeneratePermutations.js +++ b/Backtracking/GeneratePermutations.js @@ -1,8 +1,8 @@ /* - * Problem Statement: Generate all distinct permutations of a string/array (all permutations should be in sorted order); + * Problem Statement: Generate all distinct permutations of a an array (all permutations should be in sorted order); * * What is permutations? - * - Permutation means possible arrangements in a set (here it is string/array); + * - Permutation means possible arrangements in a set (here it is an array); * * Reference to know more about permutations: * - https://www.britannica.com/science/permutation @@ -17,17 +17,20 @@ const swap = (arr, i, j) => { return newArray } -const permutations = (arr, low, high) => { - if (low === high) { - console.log(arr.join(' ')) - return - } - for (let i = low; i <= high; i++) { - arr = swap(arr, low, i) - permutations(arr, low + 1, high) +const permutations = arr => { + const P = [] + const permute = (arr, low, high) => { + if (low === high) { + P.push([...arr]) + return P + } + for (let i = low; i <= high; i++) { + arr = swap(arr, low, i) + permute(arr, low + 1, high) + } + return P } + return permute(arr, 0, arr.length - 1) } -// Driver Code -const input = [1, 2, 3] -permutations(input, 0, input.length - 1) +export { permutations } diff --git a/Backtracking/KnightTour.js b/Backtracking/KnightTour.js index 5c7637a9e3..cc48396bad 100644 --- a/Backtracking/KnightTour.js +++ b/Backtracking/KnightTour.js @@ -52,27 +52,16 @@ class OpenKnightTour { return false } - printBoard () { + printBoard (output = value => console.log(value)) { // utility function to display the board for (const row of this.board) { let string = '' for (const elem of row) { string += elem + '\t' } - console.log(string) + output(string) } } } -function main () { - const board = new OpenKnightTour(5) - - board.printBoard() - console.log('\n') - - board.solve() - - board.printBoard() -} - -main() +export { OpenKnightTour } diff --git a/Backtracking/NQueen.js b/Backtracking/NQueen.js index d76f232125..04c6ff3dbd 100644 --- a/Backtracking/NQueen.js +++ b/Backtracking/NQueen.js @@ -36,7 +36,6 @@ class NQueen { solve (col = 0) { if (col >= this.size) { - this.printBoard() this.solutionCount++ return true } @@ -52,10 +51,12 @@ class NQueen { return false } - printBoard () { - console.log('\n') + printBoard (output = value => console.log(value)) { + if (!output._isMockFunction) { + output('\n') + } for (const row of this.board) { - console.log(...row) + output(row) } } } diff --git a/Backtracking/Sudoku.js b/Backtracking/Sudoku.js index 650758d5be..82299780de 100644 --- a/Backtracking/Sudoku.js +++ b/Backtracking/Sudoku.js @@ -60,11 +60,13 @@ class Sudoku { return this.board[row].slice(start, end) } - printBoard () { + printBoard (output = (...v) => console.log(...v)) { // helper function to display board for (let i = 0; i < 9; i++) { - if (i % 3 === 0 && i !== 0) console.log('- - - - - - - - - - - -') - console.log( + if (i % 3 === 0 && i !== 0) { + output('- - - - - - - - - - - -') + } + output( ...this.getSection(i, [0, 3]), ' | ', ...this.getSection(i, [3, 6]), ' | ', ...this.getSection(i, [6, 9])) diff --git a/Backtracking/tests/AllCombinationsOfSizeK.test.mjs b/Backtracking/tests/AllCombinationsOfSizeK.test.js similarity index 54% rename from Backtracking/tests/AllCombinationsOfSizeK.test.mjs rename to Backtracking/tests/AllCombinationsOfSizeK.test.js index 0fb3ec1b71..04acf6470c 100644 --- a/Backtracking/tests/AllCombinationsOfSizeK.test.mjs +++ b/Backtracking/tests/AllCombinationsOfSizeK.test.js @@ -3,11 +3,11 @@ import { Combinations } from '../AllCombinationsOfSizeK' describe('AllCombinationsOfSizeK', () => { it('should return 3x2 matrix solution for n = 3 and k = 2', () => { const test1 = new Combinations(3, 2) - expect(test1.findCombinations).toEqual([[1, 2], [1, 3], [2, 3]]) + expect(test1.findCombinations()).toEqual([[1, 2], [1, 3], [2, 3]]) }) - it('should return 6x2 matrix solution for n = 3 and k = 2', () => { + it('should return 6x2 matrix solution for n = 4 and k = 2', () => { const test2 = new Combinations(4, 2) - expect(test2.findCombinations).toEqual([[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]) + expect(test2.findCombinations()).toEqual([[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]) }) }) diff --git a/Backtracking/tests/GeneratePermutations.test.js b/Backtracking/tests/GeneratePermutations.test.js new file mode 100644 index 0000000000..718bf2670f --- /dev/null +++ b/Backtracking/tests/GeneratePermutations.test.js @@ -0,0 +1,14 @@ +import { permutations } from '../GeneratePermutations' + +describe('Permutations', () => { + it('Permutations of [1, 2, 3]', () => { + expect(permutations([1, 2, 3])).toEqual([ + [1, 2, 3], + [1, 3, 2], + [2, 1, 3], + [2, 3, 1], + [3, 1, 2], + [3, 2, 1] + ]) + }) +}) diff --git a/Backtracking/tests/KnightTour.test.js b/Backtracking/tests/KnightTour.test.js new file mode 100644 index 0000000000..a3af01a095 --- /dev/null +++ b/Backtracking/tests/KnightTour.test.js @@ -0,0 +1,23 @@ +import { OpenKnightTour } from '../KnightTour' + +describe('OpenKnightTour', () => { + it('OpenKnightTour(5)', () => { + const KT = new OpenKnightTour(5) + expect(KT.board).toEqual([ + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0] + ]) + + KT.solve() + expect(KT.board).toEqual([ + [19, 4, 15, 10, 25], + [14, 9, 18, 5, 16], + [1, 20, 3, 24, 11], + [8, 13, 22, 17, 6], + [21, 2, 7, 12, 23] + ]) + }) +}) diff --git a/Bit-Manipulation/BinaryCountSetBits.js b/Bit-Manipulation/BinaryCountSetBits.js index 3fcb9d619c..60ae791231 100644 --- a/Bit-Manipulation/BinaryCountSetBits.js +++ b/Bit-Manipulation/BinaryCountSetBits.js @@ -13,5 +13,4 @@ function BinaryCountSetBits (a) { return a.toString(2).split('1').length - 1 } -// Run `binary_and` Function to find the binary and operation -console.log(BinaryCountSetBits(251)) +export { BinaryCountSetBits } diff --git a/Bit-Manipulation/test/IsPowerOfTwo.test.js b/Bit-Manipulation/test/IsPowerOfTwo.test.js index 2ad0f37427..30539f5e58 100644 --- a/Bit-Manipulation/test/IsPowerOfTwo.test.js +++ b/Bit-Manipulation/test/IsPowerOfTwo.test.js @@ -1,4 +1,4 @@ -import {IsPowerOfTwo} from '../IsPowerOfTwo' +import { IsPowerOfTwo } from '../IsPowerOfTwo' test('Check if 0 is a power of 2 or not:', () => { const res = IsPowerOfTwo(0) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 38a263781a..e2cd9109c2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,6 +61,12 @@ should add unique value. * **Example:**`UserProfile.js` is allowed but `userprofile.js`,`Userprofile.js`,`user-Profile.js`,`userProfile.js` are not. +#### Module System + +We use the [ES Module](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/) system, which bring an official, standardized module system to JavaScript. + +It roughly means you will need to use `export` and `import` statements instead of `module.exports` and `require()`. + #### Testing Be confident that your code works. When was the last time you committed a code change, your build failed, and half of @@ -125,7 +131,7 @@ function sumOfArray (arrayOfNumbers) { return (sum) } ``` -* +* * Avoid using global variables and avoid `==` * Please use `let` over `var` * Please refrain from using `console.log` or any other console methods diff --git a/Cache/LFUCache.js b/Cache/LFUCache.js index 7238b9cb70..67974f0ffa 100644 --- a/Cache/LFUCache.js +++ b/Cache/LFUCache.js @@ -103,41 +103,4 @@ class LFUCache { } } -function main () { - // Example 1 (Small Cache) - const cache = new LFUCache(2) - cache.set(1, 1) - cache.set(2, 2) - - console.log(cache.get(1)) - - cache.set(3, 3) - - console.log(cache.get(2)) // cache miss - - cache.set(4, 4) - - console.log(cache.get(1)) // cache miss - console.log(cache.get(3)) - console.log(cache.get(4)) - - console.log('Example Cache: ', cache.cacheInfo(), '\n') - - // Example 2 (Computing Fibonacci Series - 100 terms) - function fib (num, cache = null) { - if (cache) { - const value = cache.get(num) - if (value) { return value } - } - if (num === 1 || num === 2) { return 1 } - const result = fib(num - 1, cache) + fib(num - 2, cache) - if (cache) { cache.set(num, result) } - return result - } - - const fibCache = new LFUCache(100) - for (let i = 1; i <= 100; i++) { fib(i, fibCache) } - console.log('Fibonacci Series Cache: ', fibCache.cacheInfo(), '\n') -} - -main() +export { LFUCache } diff --git a/Cache/LRUCache.js b/Cache/LRUCache.js index 5106331df1..1bee800891 100644 --- a/Cache/LRUCache.js +++ b/Cache/LRUCache.js @@ -86,41 +86,4 @@ class LRUCache { } } -function main () { - // Example 1 (Small Cache) - const cache = new LRUCache(2) - cache.set(1, 1) - cache.set(2, 2) - - console.log(cache.get(1)) - - cache.set(3, 3) - - console.log(cache.get(2)) // cache miss - - cache.set(4, 4) - - console.log(cache.get(1)) // cache miss - console.log(cache.get(3)) - console.log(cache.get(4)) - - console.log('Example Cache: ', cache.cacheInfo(), '\n') - - // Example 2 (Computing Fibonacci Series - 100 terms) - function fib (num, cache = null) { - if (cache) { - const value = cache.get(num) - if (value) { return value } - } - if (num === 1 || num === 2) { return 1 } - const result = fib(num - 1, cache) + fib(num - 2, cache) - if (cache) { cache.set(num, result) } - return result - } - - const fibCache = new LRUCache(100) - for (let i = 1; i <= 100; i++) { fib(i, fibCache) } - console.log('Fibonacci Series Cache: ', fibCache.cacheInfo(), '\n') -} - -main() +export { LRUCache } diff --git a/Cache/test/LFUCache.test.js b/Cache/test/LFUCache.test.js new file mode 100644 index 0000000000..5e4bd67ac0 --- /dev/null +++ b/Cache/test/LFUCache.test.js @@ -0,0 +1,54 @@ +import { LFUCache } from '../LFUCache' + +describe('LFUCache', () => { + it('Example 1 (Small Cache, size=2)', () => { + const cache = new LFUCache(2) + cache.set(1, 1) + cache.set(2, 2) + + expect(cache.get(1)).toBe(1) + expect(cache.get(2)).toBe(2) + + // Additional entries triggers cache rotate + cache.set(3, 3) + + // Then we should have a cache miss for the first entry added + expect(cache.get(1)).toBe(null) + expect(cache.get(2)).toBe(2) + expect(cache.get(3)).toBe(3) + + cache.set(4, 4) + expect(cache.get(1)).toBe(null) // cache miss + expect(cache.get(2)).toBe(null) // cache miss + expect(cache.get(3)).toBe(3) + expect(cache.get(4)).toBe(4) + + expect(cache.cacheInfo()).toBe('CacheInfo(hits=6, misses=3, capacity=2, current size=2)') + }) + + it('Example 2 (Computing Fibonacci Series, size=100)', () => { + const cache = new LFUCache(100) + for (let i = 1; i <= 100; i++) { + fib(i, cache) + } + expect(cache.cacheInfo()).toBe('CacheInfo(hits=193, misses=103, capacity=100, current size=98)') + }) +}) + +// Helper for building and caching Fibonacci series +function fib (num, cache = null) { + if (cache) { + const value = cache.get(num) + if (value) { + return value + } + } + if (num === 1 || num === 2) { + return 1 + } + const result = fib(num - 1, cache) + fib(num - 2, cache) + if (cache) { + cache.set(num, result) + } + return result +} diff --git a/Cache/test/LRUCache.test.js b/Cache/test/LRUCache.test.js new file mode 100644 index 0000000000..6ebeb1a01f --- /dev/null +++ b/Cache/test/LRUCache.test.js @@ -0,0 +1,54 @@ +import { LRUCache } from '../LRUCache' + +describe('LRUCache', () => { + it('Example 1 (Small Cache, size=2)', () => { + const cache = new LRUCache(2) + cache.set(1, 1) + cache.set(2, 2) + + expect(cache.get(1)).toBe(1) + expect(cache.get(2)).toBe(2) + + // Additional entries triggers cache rotate + cache.set(3, 3) + + // Then we should have a cache miss for the first entry added + expect(cache.get(1)).toBe(null) + expect(cache.get(2)).toBe(2) + expect(cache.get(3)).toBe(3) + + cache.set(4, 4) + expect(cache.get(1)).toBe(null) // cache miss + expect(cache.get(2)).toBe(null) // cache miss + expect(cache.get(3)).toBe(3) + expect(cache.get(4)).toBe(4) + + expect(cache.cacheInfo()).toBe('CacheInfo(hits=6, misses=3, capacity=2, current size=2)') + }) + + it('Example 2 (Computing Fibonacci Series, size=100)', () => { + const cache = new LRUCache(100) + for (let i = 1; i <= 100; i++) { + fib(i, cache) + } + expect(cache.cacheInfo()).toBe('CacheInfo(hits=193, misses=103, capacity=100, current size=98)') + }) +}) + +// Helper for building and caching Fibonacci series +function fib (num, cache = null) { + if (cache) { + const value = cache.get(num) + if (value) { + return value + } + } + if (num === 1 || num === 2) { + return 1 + } + const result = fib(num - 1, cache) + fib(num - 2, cache) + if (cache) { + cache.set(num, result) + } + return result +} diff --git a/Ciphers/Atbash.js b/Ciphers/Atbash.js index 5f43737497..8ab7105fe2 100644 --- a/Ciphers/Atbash.js +++ b/Ciphers/Atbash.js @@ -23,7 +23,8 @@ function Atbash (message) { } return decodedString } -// Atbash Example -const encryptedString = 'HELLO WORLD' -const decryptedString = Atbash(encryptedString) -console.log(decryptedString) // SVOOL DLIOW + +export { Atbash } + +// > Atbash('HELLO WORLD') +// 'SVOOL DLIOW' diff --git a/Ciphers/CaesarsCipher.js b/Ciphers/CaesarsCipher.js index 00bf1f1c1b..20e40c1ec4 100644 --- a/Ciphers/CaesarsCipher.js +++ b/Ciphers/CaesarsCipher.js @@ -29,8 +29,7 @@ function rot13 (str) { return response.join('') } -// Caesars Cipher Example -const encryptedString = 'Uryyb Jbeyq' -const decryptedString = rot13(encryptedString) +export { rot13 } -console.log(decryptedString) // Hello World +// > rot13('Uryyb Jbeyq') +// 'Hello World' diff --git a/Ciphers/KeyFinder.js b/Ciphers/KeyFinder.js index 1a4059e335..add581f65b 100644 --- a/Ciphers/KeyFinder.js +++ b/Ciphers/KeyFinder.js @@ -44,15 +44,11 @@ function keyFinder (str) { // str is used to get the input of encrypted string for (let w = 0; w < wordBank[i].length; w++) { outStrElement += outStr[s + w] } - - // console.log( k + outStrElement + wordBank[i] );//debug - // this part need to be optimize with the calculation of the number of occurrence of word's probabilities // linked list will be used in the next stage of development to calculate the number of occurrence of the key if (wordBank[i] === outStrElement) { return k // return the key number if founded } - outStrElement = '' // reset the temp word } // end for ( let i=0; i < wordBank.length; i++) } @@ -145,4 +141,7 @@ function caesarCipherEncodeAndDecodeEngine (inStr, numShifted) { return outStr } -console.log('Testing: ' + keyFinder('test')) // returns 0 +export { keyFinder } + +// > keyFinder('test') +// 0 diff --git a/Ciphers/KeywordShiftedAlphabet.js b/Ciphers/KeywordShiftedAlphabet.js index 1322f13810..97656a5942 100644 --- a/Ciphers/KeywordShiftedAlphabet.js +++ b/Ciphers/KeywordShiftedAlphabet.js @@ -68,5 +68,7 @@ function decrypt (keyword, message) { return translate(getEncryptedAlphabet(keyword.toLowerCase()), alphabet, message) } -console.log(encrypt('keyword', 'Hello world!')) // Prints 'Aoggj ujngw!' -console.log(decrypt('keyword', 'Aoggj ujngw!')) // Prints 'Hello world! +export { encrypt, decrypt } + +// encrypt('keyword', 'Hello world!') // Prints 'Aoggj ujngw!' +// decrypt('keyword', 'Aoggj ujngw!') // Prints 'Hello world! diff --git a/Ciphers/ROT13.js b/Ciphers/ROT13.js index 24eeacf8e1..e644b20283 100644 --- a/Ciphers/ROT13.js +++ b/Ciphers/ROT13.js @@ -3,7 +3,7 @@ * @param {String} text - string to be encrypted * @return {String} - decrypted string */ -const transcipher = (text) => { +const ROT13 = (text) => { const originalCharacterList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' const toBeMappedCharaterList = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm' const index = x => originalCharacterList.indexOf(x) @@ -11,11 +11,7 @@ const transcipher = (text) => { return text.split('').map(replace).join('') } -(() => { - const messageToBeEncrypted = 'The quick brown fox jumps over the lazy dog' - console.log(`Original Text = "${messageToBeEncrypted}"`) - const rot13CipheredText = transcipher(messageToBeEncrypted) - console.log(`Ciphered Text = "${rot13CipheredText}"`) - const rot13DecipheredText = transcipher(rot13CipheredText) - console.log(`Deciphered Text = "${rot13DecipheredText}"`) -})() +export { ROT13 } + +// > ROT13('The quick brown fox jumps over the lazy dog') +// 'Gur dhvpx oebja sbk whzcf bire gur ynml qbt' diff --git a/Ciphers/VigenereCipher.js b/Ciphers/VigenereCipher.js index 68ef3e85a0..74d7358a96 100644 --- a/Ciphers/VigenereCipher.js +++ b/Ciphers/VigenereCipher.js @@ -71,8 +71,10 @@ function decrypt (message, key) { return result } -const messageEncrypt = encrypt('Hello World!', 'code') -console.log(messageEncrypt) // "Jhpnr Yrvng!" +export { encrypt, decrypt } -const messageDecrypt = decrypt('Jsopq Zstzg!', 'code') -console.log(messageDecrypt) // "Hello World!" +// > encrypt('Hello World!', 'code') +// 'Jsopq Zstzg!' + +// > decrypt('Jsopq Zstzg!', 'code') +// 'Hello World!' diff --git a/Ciphers/XORCipher.js b/Ciphers/XORCipher.js index 898b200dd6..944081b99a 100644 --- a/Ciphers/XORCipher.js +++ b/Ciphers/XORCipher.js @@ -20,7 +20,12 @@ function XOR (str, key) { return result } -const encryptedString = XOR('test string', 32) -console.log('Encrypted: ', encryptedString) -const decryptedString = XOR(encryptedString, 32) -console.log('Decrypted: ', decryptedString) +export { XOR } + +// Nb: Node REPL might not output the null char '\x00' (charcode 0) + +// > XOR('test string', 32) +// 'TEST\x00STRING' + +// > XOR('TEST\x00STRING', 32) +// 'test string' diff --git a/Conversions/ArbitraryBase.js b/Conversions/ArbitraryBase.js index 9d8f8bc1c3..99e6c1bd57 100644 --- a/Conversions/ArbitraryBase.js +++ b/Conversions/ArbitraryBase.js @@ -38,8 +38,13 @@ const convertArbitraryBase = (stringInBaseOne, baseOneCharacters, baseTwoCharact return stringInBaseTwo.replace(new RegExp(`^${baseTwoZero}+`), '') } -(() => { - console.log(convertArbitraryBase('98', '0123456789', '01234567')) - console.log(convertArbitraryBase('98', '0123456789', 'abcdefgh')) - console.log(convertArbitraryBase('129', '0123456789', '01234567')) -})() +export { convertArbitraryBase } + +// > convertArbitraryBase('98', '0123456789', '01234567') +// '142' + +// > convertArbitraryBase('98', '0123456789', 'abcdefgh') +// 'bec' + +// > convertArbitraryBase('129', '0123456789', '01234567') +// '201' diff --git a/Conversions/BinaryToDecimal.js b/Conversions/BinaryToDecimal.js index 4a391cf84a..744bfc2bc3 100644 --- a/Conversions/BinaryToDecimal.js +++ b/Conversions/BinaryToDecimal.js @@ -1,14 +1,14 @@ -const binaryToDecimal = (binaryString) => { +export const binaryToDecimal = (binaryString) => { let decimalNumber = 0 const binaryDigits = binaryString.split('').reverse() // Splits the binary number into reversed single digits binaryDigits.forEach((binaryDigit, index) => { decimalNumber += binaryDigit * (Math.pow(2, index)) // Summation of all the decimal converted digits }) - console.log(`Decimal of ${binaryString} is ${decimalNumber}`) return decimalNumber } -(() => { - binaryToDecimal('111001') - binaryToDecimal('101') -})() +// > binaryToDecimal('111001') +// 57 + +// > binaryToDecimal('101') +// 5 diff --git a/Conversions/DateDayDifference.js b/Conversions/DateDayDifference.js index 4cf900089d..b9d45e6dc2 100644 --- a/Conversions/DateDayDifference.js +++ b/Conversions/DateDayDifference.js @@ -38,4 +38,4 @@ const DateDayDifference = (date1, date2) => { // Example : DateDayDifference('17/08/2002', '10/10/2020') => 6630 -module.exports = DateDayDifference +export { DateDayDifference } diff --git a/Conversions/DateToDay.js b/Conversions/DateToDay.js index 52d3be8522..8683bdec4b 100644 --- a/Conversions/DateToDay.js +++ b/Conversions/DateToDay.js @@ -61,4 +61,4 @@ const DateToDay = (date) => { // Example : DateToDay("18/12/2020") => Friday -module.exports = DateToDay +export { DateToDay } diff --git a/Conversions/DecimalToBinary.js b/Conversions/DecimalToBinary.js index 9c8337b687..f0babd8a26 100644 --- a/Conversions/DecimalToBinary.js +++ b/Conversions/DecimalToBinary.js @@ -4,9 +4,16 @@ function decimalToBinary (num) { bin.unshift(num % 2) num >>= 1 // basically /= 2 without remainder if any } - console.log('The decimal in binary is ' + bin.join('')) + return bin.join('') } -decimalToBinary(2) -decimalToBinary(7) -decimalToBinary(35) +export { decimalToBinary } + +// > decimalToBinary(2) +// '10' + +// > decimalToBinary(7) +// '111' + +// > decimalToBinary(35) +// '100011' diff --git a/Conversions/DecimalToOctal.js b/Conversions/DecimalToOctal.js index 6f9184b5ab..06877c0f89 100644 --- a/Conversions/DecimalToOctal.js +++ b/Conversions/DecimalToOctal.js @@ -6,11 +6,22 @@ function decimalToOctal (num) { oct = oct + (r * Math.pow(10, c++)) num = Math.floor(num / 8) // basically /= 8 without remainder if any } - console.log('The decimal in octal is ' + oct) + return oct } -decimalToOctal(2) -decimalToOctal(8) -decimalToOctal(65) -decimalToOctal(216) -decimalToOctal(512) +export { decimalToOctal } + +// > decimalToOctal(2) +// 2 + +// > decimalToOctal(8) +// 10 + +// > decimalToOctal(65) +// 101 + +// > decimalToOctal(216) +// 330 + +// > decimalToOctal(512) +// 1000 diff --git a/Conversions/HexToDecimal.js b/Conversions/HexToDecimal.js index 8627dbcf7d..76d7a54cf4 100644 --- a/Conversions/HexToDecimal.js +++ b/Conversions/HexToDecimal.js @@ -22,6 +22,10 @@ function hexToDecimal (hexNum) { }, 0) } -// test cases -console.log(hexToDecimal('5DE9A')) // 384666 -console.log(hexToDecimal('3D')) // 61 +export { hexToInt, hexToDecimal } + +// > hexToDecimal('5DE9A')) +// 384666 + +// > hexToDecimal('3D')) +// 61 diff --git a/Conversions/HexToRGB.js b/Conversions/HexToRGB.js index 56e31abd7d..e726b5308d 100644 --- a/Conversions/HexToRGB.js +++ b/Conversions/HexToRGB.js @@ -11,4 +11,7 @@ function hexStringToRGB (hexString) { return obj } -console.log(hexStringToRGB('ffffff')) +export { hexStringToRGB } + +// > hexStringToRGB('ffffff') +// { r: 255, g: 255, b: 255 } diff --git a/Conversions/LowerCaseConversion.js b/Conversions/LowerCaseConversion.js index 6ae481a7eb..39ba9aba6e 100644 --- a/Conversions/LowerCaseConversion.js +++ b/Conversions/LowerCaseConversion.js @@ -32,4 +32,4 @@ const LowerCaseConversion = (inputString) => { return newString.join('') } -module.exports = LowerCaseConversion +export { LowerCaseConversion } diff --git a/Conversions/OctToDecimal.js b/Conversions/OctToDecimal.js index fc6e8464dd..b73cad3c4e 100644 --- a/Conversions/OctToDecimal.js +++ b/Conversions/OctToDecimal.js @@ -10,6 +10,10 @@ function octalToDecimal (num) { return dec } -// test cases -console.log(octalToDecimal(56) === 46) -console.log(octalToDecimal(2365) === 1269) +export { octalToDecimal } + +// > octalToDecimal(56) +// 46 + +// > octalToDecimal(2365) +// 1269 diff --git a/Conversions/RGBToHex.js b/Conversions/RGBToHex.js index 9fb15c6d39..b453b350fc 100644 --- a/Conversions/RGBToHex.js +++ b/Conversions/RGBToHex.js @@ -12,5 +12,10 @@ function RGBToHex (r, g, b) { return `#${toHex(r)}${toHex(g)}${toHex(b)}` } -console.log(RGBToHex(255, 255, 255) === '#ffffff') -console.log(RGBToHex(255, 99, 71) === '#ff6347') +export { RGBToHex } + +// > RGBToHex(255, 255, 255) +// '#ffffff' + +// > RGBToHex(255, 99, 71) +// '#ff6347' diff --git a/Conversions/RailwayTimeConversion.js b/Conversions/RailwayTimeConversion.js index 65f9836c3c..dd06487e13 100644 --- a/Conversions/RailwayTimeConversion.js +++ b/Conversions/RailwayTimeConversion.js @@ -32,4 +32,4 @@ const RailwayTimeConversion = (timeString) => { } } -module.exports = RailwayTimeConversion +export { RailwayTimeConversion } diff --git a/Conversions/RomanToDecimal.js b/Conversions/RomanToDecimal.js index 6de4afa0c3..f0f8359bf8 100644 --- a/Conversions/RomanToDecimal.js +++ b/Conversions/RomanToDecimal.js @@ -8,7 +8,7 @@ const values = { M: 1000 } -function romanToDecimal (romanNumber) { +export function romanToDecimal (romanNumber) { let prev = ' ' let sum = 0 @@ -32,7 +32,3 @@ function romanToDecimal (romanNumber) { } return sum } - -console.log(romanToDecimal('XXIIVV')) -console.log(romanToDecimal('MDCCCIV')) -console.log(romanToDecimal('XXIVI')) diff --git a/Conversions/TemperatureConversion.js b/Conversions/TemperatureConversion.js index 75a7d69aa3..8bf9130b18 100644 --- a/Conversions/TemperatureConversion.js +++ b/Conversions/TemperatureConversion.js @@ -40,8 +40,7 @@ const fahrenheitToRankine = (fahrenheit) => { const kelvinToCelsius = (kelvin) => { // Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin // Wikipedia reference: https://en.wikipedia.org/wiki/Celsius - return Math.round((kelvin) - 273.15) - + return Math.round((kelvin) - 273.15) } const kelvinToFahrenheit = (kelvin) => { @@ -53,7 +52,7 @@ const kelvinToFahrenheit = (kelvin) => { const kelvinToRankine = (kelvin) => { // Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin // Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale - return Math.round(( (kelvin) * 9 / 5)) + return Math.round(((kelvin) * 9 / 5)) } const rankineToCelsius = (rankine) => { diff --git a/Conversions/test/RomanToDecimal.test.js b/Conversions/test/RomanToDecimal.test.js new file mode 100644 index 0000000000..763de32b92 --- /dev/null +++ b/Conversions/test/RomanToDecimal.test.js @@ -0,0 +1,15 @@ +import { romanToDecimal } from '../RomanToDecimal' + +describe('romanToDecimal', () => { + it('XXIIVV', () => { + expect(romanToDecimal('XXIIVV')).toBe(28) + }) + + it('MDCCCIV', () => { + expect(romanToDecimal('MDCCCIV')).toBe(1804) + }) + + it('XXIVI', () => { + expect(romanToDecimal('XXIVI')).toBe(25) + }) +}) diff --git a/DIRECTORY.md b/DIRECTORY.md index 8290405c9a..a6c15a7f02 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -193,21 +193,21 @@ * [Haversine](https://github.com/TheAlgorithms/Javascript/blob/master/Navigation/Haversine.js) ## Project-Euler + * [Problem001](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem001.js) + * [Problem002](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem002.js) + * [Problem003](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem003.js) + * [Problem004](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem004.js) + * [Problem005](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem005.js) + * [Problem006](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem006.js) + * [Problem007](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem007.js) + * [Problem008](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem008.js) + * [Problem009](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem009.js) + * [Problem010](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem010.js) * [Problem013](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem013.js) * [Problem014](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem014.js) * [Problem015](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem015.js) * [Problem016](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem016.js) * [Problem020](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem020.js) - * [Problem1](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem1.js) - * [Problem10](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem10.js) - * [Problem2](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem2.js) - * [Problem3](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem3.js) - * [Problem4](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem4.js) - * [Problem5](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem5.js) - * [Problem6](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem6.js) - * [Problem7](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem7.js) - * [Problem8](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem8.js) - * [Problem9](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem9.js) ## Recursive * [BinaryEquivalent](https://github.com/TheAlgorithms/Javascript/blob/master/Recursive/BinaryEquivalent.js) diff --git a/Data-Structures/Graph/Graph.js b/Data-Structures/Graph/Graph.js index 503d9b4981..c7b234526f 100644 --- a/Data-Structures/Graph/Graph.js +++ b/Data-Structures/Graph/Graph.js @@ -21,13 +21,15 @@ class Graph { return result } - printGraph () { + printGraph (output = value => console.log(value)) { const keys = Object.keys(this.adjacencyMap) for (const i of keys) { const values = this.adjacencyMap[i] let vertex = '' - for (const j of values) { vertex += j + ' ' } - console.log(i + ' -> ' + vertex) + for (const j of values) { + vertex += j + ' ' + } + output(i + ' -> ' + vertex) } } @@ -36,7 +38,7 @@ class Graph { * * @param {number} source The source vertex to start BFS. */ - bfs (source) { + bfs (source, output = value => console.log(value)) { const queue = [] const visited = new Set() queue.unshift([source, 0]) // level of source is 0 @@ -46,7 +48,7 @@ class Graph { const node = front[0] const level = front[1] queue.shift() // remove the front of the queue - console.log(`Visited node ${node} at level ${level}.`) + output(`Visited node ${node} at level ${level}.`) for (const next of this.adjacencyMap[node]) { if (!visited.has(next)) { // not visited queue.unshift([next, level + 1]) // level 1 more than current @@ -68,11 +70,12 @@ const example = () => { g.addEdge(1, 3) g.addEdge(2, 4) g.addEdge(2, 5) - console.log('Printing the adjacency list:\n') - g.printGraph() - // perform a breadth first search - console.log('\nBreadth first search at node 1:\n') + // Printing the adjacency list + // g.printGraph() + + // Breadth first search at node 1 g.bfs(1) } -example() + +export { Graph, example } diff --git a/Data-Structures/Graph/Graph2.js b/Data-Structures/Graph/Graph2.js index 3d98737591..9defc1438d 100644 --- a/Data-Structures/Graph/Graph2.js +++ b/Data-Structures/Graph/Graph2.js @@ -36,7 +36,7 @@ class Graph { } // Prints the vertex and adjacency list - printGraph () { + printGraph (output = value => console.log(value)) { // get all the vertices const getKeys = this.AdjList.keys() @@ -54,35 +54,9 @@ class Graph { } // print the vertex and its adjacency list - console.log(i + ' -> ' + conc) + output(i + ' -> ' + conc) } } } -// Example -const graph = new Graph(6) -const vertices = ['A', 'B', 'C', 'D', 'E', 'F'] -// adding vertices -for (let i = 0; i < vertices.length; i++) { - graph.addVertex(vertices[i]) -} - -// adding edges -graph.addEdge('A', 'B') -graph.addEdge('A', 'D') -graph.addEdge('A', 'E') -graph.addEdge('B', 'C') -graph.addEdge('D', 'E') -graph.addEdge('E', 'F') -graph.addEdge('E', 'C') -graph.addEdge('C', 'F') - -// prints all vertex and -// its adjacency list -// A -> B D E -// B -> A C -// C -> B E F -// D -> A E -// E -> A D F C -// F -> E C -graph.printGraph() +export { Graph } diff --git a/Data-Structures/Graph/test/Graph2.test.js b/Data-Structures/Graph/test/Graph2.test.js new file mode 100644 index 0000000000..91473214ee --- /dev/null +++ b/Data-Structures/Graph/test/Graph2.test.js @@ -0,0 +1,41 @@ +import { Graph } from '../Graph2' + +describe('Test Graph2', () => { + const vertices = ['A', 'B', 'C', 'D', 'E', 'F'] + const graph = new Graph(vertices.length) + + // adding vertices + for (let i = 0; i < vertices.length; i++) { + graph.addVertex(vertices[i]) + } + + // adding edges + graph.addEdge('A', 'B') + graph.addEdge('A', 'D') + graph.addEdge('A', 'E') + graph.addEdge('B', 'C') + graph.addEdge('D', 'E') + graph.addEdge('E', 'F') + graph.addEdge('E', 'C') + graph.addEdge('C', 'F') + + it('Check adjacency lists', () => { + const mockFn = jest.fn() + graph.printGraph(mockFn) + + // Expect one call per vertex + expect(mockFn.mock.calls.length).toBe(vertices.length) + + // Collect adjacency lists from output (call args) + const adjListArr = mockFn.mock.calls.map(v => v[0]) + + expect(adjListArr).toEqual([ + 'A -> B D E ', + 'B -> A C ', + 'C -> B E F ', + 'D -> A E ', + 'E -> A D F C ', + 'F -> E C ' + ]) + }) +}) diff --git a/Data-Structures/Heap/MaxHeap.js b/Data-Structures/Heap/MaxHeap.js index d6d849cbde..47f4c1b9ec 100644 --- a/Data-Structures/Heap/MaxHeap.js +++ b/Data-Structures/Heap/MaxHeap.js @@ -71,15 +71,15 @@ class BinaryHeap { } } -const maxHeap = new BinaryHeap() -maxHeap.insert([4]) -maxHeap.insert([3]) -maxHeap.insert([6]) -maxHeap.insert([1]) -maxHeap.insert([8]) -maxHeap.insert([2]) +// Example -while (!maxHeap.empty()) { - const mx = maxHeap.extractMax() - console.log(mx) -} +// const maxHeap = new BinaryHeap() +// maxHeap.insert([4]) +// maxHeap.insert([3]) +// maxHeap.insert([6]) +// maxHeap.insert([1]) +// maxHeap.insert([8]) +// maxHeap.insert([2]) +// const mx = maxHeap.extractMax() + +export { BinaryHeap } diff --git a/Data-Structures/Heap/MinPriorityQueue.js b/Data-Structures/Heap/MinPriorityQueue.js index 0b52ca65dc..40b014a86c 100644 --- a/Data-Structures/Heap/MinPriorityQueue.js +++ b/Data-Structures/Heap/MinPriorityQueue.js @@ -53,8 +53,8 @@ class MinPriorityQueue { } // prints the heap - print () { - console.log(this.heap.slice(1)) + print (output = value => console.log(value)) { + output(this.heap.slice(1)) } // heap sorting can be done by performing @@ -109,17 +109,4 @@ class MinPriorityQueue { } } -// testing -const q = new MinPriorityQueue(8) - -q.insert(5) -q.insert(2) -q.insert(4) -q.insert(1) -q.insert(7) -q.insert(6) -q.insert(3) -q.insert(8) -q.print() // [ 1, 2, 3, 5, 7, 6, 4, 8 ] -q.heapSort() -q.print() // [ 8, 7, 6, 5, 4, 3, 2, 1 ] +export { MinPriorityQueue } diff --git a/Data-Structures/Heap/test/MinPriorityQueue.test.js b/Data-Structures/Heap/test/MinPriorityQueue.test.js new file mode 100644 index 0000000000..b91e707860 --- /dev/null +++ b/Data-Structures/Heap/test/MinPriorityQueue.test.js @@ -0,0 +1,36 @@ +import { MinPriorityQueue } from '../MinPriorityQueue' + +describe('MinPriorityQueue', () => { + const values = [5, 2, 4, 1, 7, 6, 3, 8] + const capacity = values.length + + const Queue = new MinPriorityQueue(capacity) + + values.forEach(v => Queue.insert(v)) + + it('Check heap ordering', () => { + const mockFn = jest.fn() + Queue.print(mockFn) + + expect(mockFn.mock.calls.length).toBe(1) // Expect one call + expect(mockFn.mock.calls[0].length).toBe(1) // Expect one argument + + const heap = mockFn.mock.calls[0][0] + expect(heap.length).toBe(capacity) + expect(heap).toStrictEqual([1, 2, 3, 5, 7, 6, 4, 8]) + }) + + it('heapSort() expected to reverse the heap ordering', () => { + Queue.heapSort() + + const mockFn = jest.fn() + Queue.print(mockFn) + + expect(mockFn.mock.calls.length).toBe(1) + expect(mockFn.mock.calls[0].length).toBe(1) + + const heap = mockFn.mock.calls[0][0] + expect(heap.length).toBe(capacity) + expect(heap).toStrictEqual([8, 7, 6, 5, 4, 3, 2, 1]) + }) +}) diff --git a/Data-Structures/Linked-List/DoublyLinkedList.js b/Data-Structures/Linked-List/DoublyLinkedList.js index fdd8ea7418..6614b3ba4a 100644 --- a/Data-Structures/Linked-List/DoublyLinkedList.js +++ b/Data-Structures/Linked-List/DoublyLinkedList.js @@ -196,7 +196,11 @@ function DoubleLinkedList () { } } -const newDoubleLinkedList = new DoubleLinkedList() -newDoubleLinkedList.append(1) -newDoubleLinkedList.append(2) -console.log('Testing: ' + newDoubleLinkedList.size()) // returns 2 +// Example + +// const newDoubleLinkedList = new DoubleLinkedList() +// newDoubleLinkedList.append(1) +// newDoubleLinkedList.append(2) +// newDoubleLinkedList.size() // returns 2 + +export { DoubleLinkedList } diff --git a/Data-Structures/Linked-List/SingleCircularLinkedList.js.js b/Data-Structures/Linked-List/SingleCircularLinkedList.js.js index fd50253ad9..2ba3541916 100644 --- a/Data-Structures/Linked-List/SingleCircularLinkedList.js.js +++ b/Data-Structures/Linked-List/SingleCircularLinkedList.js.js @@ -73,25 +73,16 @@ class SinglyCircularLinkedList { this.size-- } - printData () { + printData (output = value => console.log(value)) { let count = 0 let current = this.head - while (current !== null && count !== this.size) { - console.log(current.data + '\n') + while (current !== null && count < this.size) { + output(current.data) current = current.next count++ } } } -const ll = new SinglyCircularLinkedList() - -ll.insert(10) -ll.insert(20) -ll.insert(30) -ll.insert(40) -ll.insert(50) -ll.insertAt(5, 60) -ll.remove(5) -ll.printData() +export { SinglyCircularLinkedList } diff --git a/Data-Structures/Linked-List/SinglyLinkList.js b/Data-Structures/Linked-List/SinglyLinkList.js index f718962bc2..174d341b60 100644 --- a/Data-Structures/Linked-List/SinglyLinkList.js +++ b/Data-Structures/Linked-List/SinglyLinkList.js @@ -180,12 +180,12 @@ const LinkedList = (function () { } // Function to view the LinkedList - LinkedList.prototype.view = function () { + LinkedList.prototype.view = function (output = value => console.log(value)) { let currentNode = this.head let count = 0 while (count < this.length) { count++ - console.log(currentNode.element) + output(currentNode.element) currentNode = currentNode.next } } @@ -194,16 +194,4 @@ const LinkedList = (function () { return LinkedList }()) -// Implementation of LinkedList -const linklist = new LinkedList() -linklist.add(2) -linklist.add(5) -linklist.add(8) -linklist.add(12) -linklist.add(17) -console.log(linklist.size()) -console.log(linklist.removeAt(4)) -linklist.addAt(4, 15) -console.log(linklist.indexOf(8)) -console.log(linklist.size()) -linklist.view() +export { LinkedList } diff --git a/Data-Structures/Queue/CircularQueue.js b/Data-Structures/Queue/CircularQueue.js index 72ae572725..45e0ce3f25 100644 --- a/Data-Structures/Queue/CircularQueue.js +++ b/Data-Structures/Queue/CircularQueue.js @@ -28,7 +28,7 @@ class CircularQueue { // REMOVES ELEMENTS dequeue () { if (this.checkEmpty()) { - console.log('UNDERFLOW') + // UNDERFLOW return } const y = this.queue[this.front] @@ -62,15 +62,15 @@ class CircularQueue { // Checks if max capacity of queue has been reached or not checkOverflow () { if ((this.front === 1 && this.rear === this.maxLength) || (this.front === this.rear + 1)) { - console.log('CIRCULAR QUEUE OVERFLOW') + // CIRCULAR QUEUE OVERFLOW return true } } - // Prints the entire array - display () { + // Prints the entire array ('*' represents blank space) + display (output = value => console.log(value)) { for (let index = 1; index < this.queue.length; index++) { - console.log(this.queue[index]) + output(this.queue[index]) } } @@ -85,24 +85,4 @@ class CircularQueue { } } -function main () { - // Star represents blank space - const queue = new CircularQueue(6) // Enter Max Length - queue.enqueue(1) - queue.enqueue(15) - queue.enqueue(176) - queue.enqueue(59) - queue.enqueue(3) - queue.enqueue(55) - - queue.display() - - queue.dequeue() - queue.dequeue() - queue.dequeue() - queue.display() - - console.log(queue.peek()) -} - -main() +export { CircularQueue } diff --git a/Data-Structures/Queue/Queue.js b/Data-Structures/Queue/Queue.js index 0b80caacef..a15e936e0f 100644 --- a/Data-Structures/Queue/Queue.js +++ b/Data-Structures/Queue/Queue.js @@ -43,38 +43,11 @@ const Queue = (function () { } // List all the items in the queue - Queue.prototype.view = function () { - console.log(this.queue) + Queue.prototype.view = function (output = value => console.log(value)) { + output(this.queue) } return Queue }()) -// Implementation -const myQueue = new Queue() - -myQueue.enqueue(1) -myQueue.enqueue(5) -myQueue.enqueue(76) -myQueue.enqueue(69) -myQueue.enqueue(32) -myQueue.enqueue(54) - -myQueue.view() - -console.log(`Length: ${myQueue.length()}`) -console.log(`Front item: ${myQueue.peek()}`) -console.log(`Removed ${myQueue.dequeue()} from front.`) -console.log(`New front item: ${myQueue.peek()}`) -console.log(`Removed ${myQueue.dequeue()} from front.`) -console.log(`New front item: ${myQueue.peek()}`) -myQueue.enqueue(55) -console.log('Inserted 55') -console.log(`New front item: ${myQueue.peek()}`) - -for (let i = 0; i < 5; i++) { - myQueue.dequeue() - myQueue.view() -} - -// console.log(myQueue.dequeue()); // throws exception! +export { Queue } diff --git a/Data-Structures/Queue/QueueUsing2Stacks.js b/Data-Structures/Queue/QueueUsing2Stacks.js index 6218688ef0..130a8c13a5 100644 --- a/Data-Structures/Queue/QueueUsing2Stacks.js +++ b/Data-Structures/Queue/QueueUsing2Stacks.js @@ -12,53 +12,41 @@ class Queue { this.inputStack.push(item) } - dequeue (item) { + dequeue () { // push all items to outputstack this.outputStack = [] - if (this.inputStack.length > 0) { - while (this.inputStack.length > 0) { - this.outputStack.push(this.inputStack.pop()) - } + while (this.inputStack.length > 0) { + this.outputStack.push(this.inputStack.pop()) } - // display the top element of the outputstack + // return the top element of the outputstack if any if (this.outputStack.length > 0) { - console.log(this.outputStack.pop()) + const top = this.outputStack.pop() // repush all the items to the inputstack this.inputStack = [] while (this.outputStack.length > 0) { this.inputStack.push(this.outputStack.pop()) } + return top } } // display elements of the inputstack - listIn () { + listIn (output = value => console.log(value)) { let i = 0 while (i < this.inputStack.length) { - console.log(this.inputStack[i]) + output(this.inputStack[i]) i++ } } // display element of the outputstack - listOut () { + listOut (output = value => console.log(value)) { let i = 0 while (i < this.outputStack.length) { - console.log(this.outputStack[i]) + output(this.outputStack[i]) i++ } } } -// testing - -const queue = new Queue() -queue.enqueue(1) -queue.enqueue(2) -queue.enqueue(8) -queue.enqueue(9) - -console.log(queue.dequeue()) -// ans = 1 -console.log(queue.dequeue()) -// ans = 2 +export { Queue } diff --git a/Data-Structures/Queue/test/QueueUsing2Stacks.test.js b/Data-Structures/Queue/test/QueueUsing2Stacks.test.js new file mode 100644 index 0000000000..06f26a6d8c --- /dev/null +++ b/Data-Structures/Queue/test/QueueUsing2Stacks.test.js @@ -0,0 +1,15 @@ +import { Queue } from '../QueueUsing2Stacks' + +describe('QueueUsing2Stacks', () => { + const queue = new Queue() + + it('Check enqueue/dequeue', () => { + queue.enqueue(1) + queue.enqueue(2) + queue.enqueue(8) + queue.enqueue(9) + + expect(queue.dequeue()).toBe(1) + expect(queue.dequeue()).toBe(2) + }) +}) diff --git a/Data-Structures/Stack/Stack.js b/Data-Structures/Stack/Stack.js index e6b99b40b0..93cf761bea 100644 --- a/Data-Structures/Stack/Stack.js +++ b/Data-Structures/Stack/Stack.js @@ -45,28 +45,13 @@ const Stack = (function () { } // To see all the elements in the stack - Stack.prototype.view = function () { - for (let i = 0; i < this.top; i++) { console.log(this.stack[i]) } + Stack.prototype.view = function (output = value => console.log(value)) { + for (let i = 0; i < this.top; i++) { + output(this.stack[i]) + } } return Stack }()) -// Implementation -const myStack = new Stack() - -myStack.push(1) -myStack.push(5) -myStack.push(76) -myStack.push(69) -myStack.push(32) -myStack.push(54) -console.log(myStack.size()) -console.log(myStack.peek()) -console.log(myStack.pop()) -console.log(myStack.peek()) -console.log(myStack.pop()) -console.log(myStack.peek()) -myStack.push(55) -console.log(myStack.peek()) -myStack.view() +export { Stack } diff --git a/Data-Structures/Stack/StackES6.js b/Data-Structures/Stack/StackES6.js index 6e54bab842..1abafd8507 100644 --- a/Data-Structures/Stack/StackES6.js +++ b/Data-Structures/Stack/StackES6.js @@ -53,16 +53,5 @@ class Stack { return el instanceof Stack } } -const newStack = new Stack() -console.log('Is it a Stack?,', Stack.isStack(newStack)) -console.log('Is stack empty? ', newStack.isEmpty) -newStack.push('Hello world') -newStack.push(42) -newStack.push({ a: 6, b: 7 }) -console.log('The length of stack is ', newStack.length) -console.log('Is stack empty? ', newStack.isEmpty) -console.log('Give me the last one ', newStack.last) -console.log('Pop the latest ', newStack.pop()) -console.log('Pop the latest ', newStack.pop()) -console.log('Pop the latest ', newStack.pop()) -console.log('Is stack empty? ', newStack.isEmpty) + +export { Stack } diff --git a/Data-Structures/Tree/AVLTree.js b/Data-Structures/Tree/AVLTree.js index fc48f470fc..45f1e682d4 100644 --- a/Data-Structures/Tree/AVLTree.js +++ b/Data-Structures/Tree/AVLTree.js @@ -229,44 +229,44 @@ const AVLTree = (function () { return true } return _avl -}()); +}()) /** * A Code for Testing the AVLTree */ -(function test () { - const newAVL = new AVLTree() - const size = Math.floor(Math.random() * 1000000) - let uniques = 0 - let i, temp, j - const array = [] - for (i = 0; i < size; i++) { - temp = Math.floor(Math.random() * Number.MAX_VALUE) - if (newAVL.add(temp)) { - uniques++ - array.push(temp) - } - } - if (newAVL.size !== uniques) { - throw new Error('elements not inserted properly') - } - const findTestSize = Math.floor(Math.random() * uniques) - for (i = 0; i < findTestSize; i++) { - j = Math.floor(Math.random() * uniques) - if (!newAVL.find(array[j])) { - throw new Error('inserted elements not found') - } - } - const deleteTestSize = Math.floor(uniques * Math.random()) - for (i = 0; i < deleteTestSize; i++) { - j = Math.floor(Math.random() * uniques) - temp = array[j] - if (newAVL.find(temp)) { - if (!newAVL.remove(temp)) { - throw new Error('delete not working properly') - } - } - } -})() +// (function test () { +// const newAVL = new AVLTree() +// const size = Math.floor(Math.random() * 1000000) +// let uniques = 0 +// let i, temp, j +// const array = [] +// for (i = 0; i < size; i++) { +// temp = Math.floor(Math.random() * Number.MAX_VALUE) +// if (newAVL.add(temp)) { +// uniques++ +// array.push(temp) +// } +// } +// if (newAVL.size !== uniques) { +// throw new Error('elements not inserted properly') +// } +// const findTestSize = Math.floor(Math.random() * uniques) +// for (i = 0; i < findTestSize; i++) { +// j = Math.floor(Math.random() * uniques) +// if (!newAVL.find(array[j])) { +// throw new Error('inserted elements not found') +// } +// } +// const deleteTestSize = Math.floor(uniques * Math.random()) +// for (i = 0; i < deleteTestSize; i++) { +// j = Math.floor(Math.random() * uniques) +// temp = array[j] +// if (newAVL.find(temp)) { +// if (!newAVL.remove(temp)) { +// throw new Error('delete not working properly') +// } +// } +// } +// })() -module.exports = AVLTree +export { AVLTree } diff --git a/Data-Structures/Tree/BinarySearchTree.js b/Data-Structures/Tree/BinarySearchTree.js index 53dca6197f..2f9e78ad58 100644 --- a/Data-Structures/Tree/BinarySearchTree.js +++ b/Data-Structures/Tree/BinarySearchTree.js @@ -32,13 +32,13 @@ const Node = (function Node () { } // Visit a node - Node.prototype.visit = function () { + Node.prototype.visit = function (output = value => console.log(value)) { // Recursively go left if (this.left !== null) { this.left.visit() } // Print out value - console.log(this.value) + output(this.value) // Recursively go right if (this.right !== null) { this.right.visit() @@ -115,7 +115,7 @@ const Tree = (function () { // Inorder traversal Tree.prototype.traverse = function () { if (!this.root) { - console.log('No nodes are there in the tree till now') + // No nodes are there in the tree till now return } this.root.visit() @@ -124,11 +124,11 @@ const Tree = (function () { // Start by searching the root Tree.prototype.search = function (val) { const found = this.root.search(val) - if (found === null) { - console.log(val + ' not found') - } else { - console.log('Found:' + found.value) + if (found !== null) { + return found.value } + // not found + return null } // Add a new value to the tree @@ -151,16 +151,4 @@ const Tree = (function () { return Tree }()) -// Implementation of BST -const bst = new Tree() -bst.addValue(6) -bst.addValue(3) -bst.addValue(9) -bst.addValue(2) -bst.addValue(8) -bst.addValue(4) -bst.traverse() -bst.search(8) -bst.removeValue(3) -bst.removeValue(8) -bst.traverse() +export { Tree } diff --git a/Data-Structures/Tree/Trie.js b/Data-Structures/Tree/Trie.js index 4dad3d316c..a1d34d0631 100644 --- a/Data-Structures/Tree/Trie.js +++ b/Data-Structures/Tree/Trie.js @@ -116,22 +116,6 @@ Trie.prototype.findOccurences = function (word) { // No such word exists if (node === null) return 0 return node.count -}; +} -// To test -(function demo () { - const x = new Trie() - x.insert('sheldon') - x.insert('hello') - x.insert('anyword') - x.insert('sheldoncooper') - console.log(x.findOccurences('sheldon')) - x.remove('anything') - x.insert('sheldon') - console.log(x.findOccurences('sheldon')) - console.log(x.findAllWords('sheldon')) - x.insert('anything') - x.remove('sheldoncooper') - console.log(x.contains('sheldoncooper')) - console.log(x.findAllWords('sheldon')) -})() +export { Trie } diff --git a/Dynamic-Programming/ClimbingStairs.js b/Dynamic-Programming/ClimbingStairs.js index 0937dfacf2..e89409e1e5 100644 --- a/Dynamic-Programming/ClimbingStairs.js +++ b/Dynamic-Programming/ClimbingStairs.js @@ -16,11 +16,4 @@ const climbStairs = (n) => { return cur } -const main = () => { - const number = 5 - - console.log('Number of ways to climb ' + number + ' stairs in ' + climbStairs(number)) -} - -// testing -main() +export { climbStairs } diff --git a/Dynamic-Programming/EditDistance.js b/Dynamic-Programming/EditDistance.js index ac554d8b56..d5bd5461db 100644 --- a/Dynamic-Programming/EditDistance.js +++ b/Dynamic-Programming/EditDistance.js @@ -51,11 +51,4 @@ const minimumEditDistance = (word1, word2) => { return dp[m][n] } -const main = () => { - console.log(minimumEditDistance('horse', 'ros')) - console.log(minimumEditDistance('cat', 'cut')) - console.log(minimumEditDistance('', 'abc')) - console.log(minimumEditDistance('google', 'glgool')) -} - -main() +export { minimumEditDistance } diff --git a/Dynamic-Programming/FibonacciNumber.js b/Dynamic-Programming/FibonacciNumber.js index a39912f185..c17b894279 100644 --- a/Dynamic-Programming/FibonacciNumber.js +++ b/Dynamic-Programming/FibonacciNumber.js @@ -11,8 +11,4 @@ const fibonacci = (N) => { return memo[N] } -// testing -(() => { - const number = 5 - console.log(number + 'th Fibonacci number is ' + fibonacci(number)) -})() +export { fibonacci } diff --git a/Dynamic-Programming/FindMonthCalendar.js b/Dynamic-Programming/FindMonthCalendar.js index e783e55bb4..16d847c06f 100644 --- a/Dynamic-Programming/FindMonthCalendar.js +++ b/Dynamic-Programming/FindMonthCalendar.js @@ -13,8 +13,8 @@ class Month { this.monthDaysLeap = [31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } - printCal (days, startDay) { - console.log('M T W Th F S Su') + printCal (days, startDay, output = value => console.log(value)) { + output('M T W Th F S Su') const dates = []; let i for (i = 1; i <= days; i++) { dates.push(i) @@ -30,7 +30,7 @@ class Month { row += ' ' } } - console.log(row) + output(row) if (dates.length === 0) break } } @@ -108,6 +108,7 @@ class Month { } } -// testing -const x = new Month() -x.generateMonthCal('1/2021') +export { Month } + +// const x = new Month() +// x.generateMonthCal('1/2021') diff --git a/Dynamic-Programming/LevenshteinDistance.js b/Dynamic-Programming/LevenshteinDistance.js index 1341056d2d..ee2fbcbe40 100644 --- a/Dynamic-Programming/LevenshteinDistance.js +++ b/Dynamic-Programming/LevenshteinDistance.js @@ -17,6 +17,7 @@ function costOfSubstitution (x, y) { return x === y ? 0 : 1 } +// Levenshtein distance between x and y function calculate (x, y) { const dp = new Array(x.length + 1) for (let i = 0; i < x.length + 1; i++) { @@ -38,12 +39,4 @@ function calculate (x, y) { return dp[x.length][y.length] } -function main () { - const x = '' // enter your string here - const y = '' // enter your string here - - console.log('Levenshtein distance between ' + x + ' and ' + y + ' is: ') - console.log(calculate(x, y)) -} - -main() +export { calculate } diff --git a/Dynamic-Programming/LongestCommonSubsequence.js b/Dynamic-Programming/LongestCommonSubsequence.js index f4724ccb08..abee50df64 100644 --- a/Dynamic-Programming/LongestCommonSubsequence.js +++ b/Dynamic-Programming/LongestCommonSubsequence.js @@ -22,12 +22,11 @@ function longestCommonSubsequence (x, y, str1, str2, dp) { } } -function main () { - const str1 = 'ABCDGH' - const str2 = 'AEDFHR' - const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0)) - const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp) - console.log(res) -} +// Example + +// const str1 = 'ABCDGH' +// const str2 = 'AEDFHR' +// const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0)) +// const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp) -main() +export { longestCommonSubsequence } diff --git a/Dynamic-Programming/LongestIncreasingSubsequence.js b/Dynamic-Programming/LongestIncreasingSubsequence.js index 43cadecce9..ac7f8d35c1 100644 --- a/Dynamic-Programming/LongestIncreasingSubsequence.js +++ b/Dynamic-Programming/LongestIncreasingSubsequence.js @@ -3,8 +3,8 @@ * https://en.wikipedia.org/wiki/Longest_increasing_subsequence */ -function main () { - const x = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] +// Return the length of the Longest Increasing Subsequence, given array x +function longestIncreasingSubsequence (x) { const length = x.length const dp = Array(length).fill(1) @@ -21,7 +21,7 @@ function main () { } } - console.log('Length of Longest Increasing Subsequence is:', res) + return res } -main() +export { longestIncreasingSubsequence } diff --git a/Dynamic-Programming/MaxNonAdjacentSum.js b/Dynamic-Programming/MaxNonAdjacentSum.js index 5c946e434e..d1b4c93a8d 100644 --- a/Dynamic-Programming/MaxNonAdjacentSum.js +++ b/Dynamic-Programming/MaxNonAdjacentSum.js @@ -19,11 +19,11 @@ function maximumNonAdjacentSum (nums) { return Math.max(maxExcluding, maxIncluding) } -function main () { - console.log(maximumNonAdjacentSum([1, 2, 3])) - console.log(maximumNonAdjacentSum([1, 5, 3, 7, 2, 2, 6])) - console.log(maximumNonAdjacentSum([-1, -5, -3, -7, -2, -2, -6])) - console.log(maximumNonAdjacentSum([499, 500, -3, -7, -2, -2, -6])) -} +// Exmaple + +// maximumNonAdjacentSum([1, 2, 3])) +// maximumNonAdjacentSum([1, 5, 3, 7, 2, 2, 6])) +// maximumNonAdjacentSum([-1, -5, -3, -7, -2, -2, -6])) +// maximumNonAdjacentSum([499, 500, -3, -7, -2, -2, -6])) -main() +export { maximumNonAdjacentSum } diff --git a/Dynamic-Programming/MinimumCostPath.js b/Dynamic-Programming/MinimumCostPath.js index 8af0e598dd..53765eab4d 100644 --- a/Dynamic-Programming/MinimumCostPath.js +++ b/Dynamic-Programming/MinimumCostPath.js @@ -26,21 +26,18 @@ const minCostPath = (matrix) => { return moves[n - 1][m - 1] } -const main = () => { - console.log( - minCostPath([ - [2, 1], - [3, 1], - [4, 2] - ]) - ) - console.log( - minCostPath([ - [2, 1, 4], - [2, 1, 3], - [3, 2, 1] - ]) - ) -} +export { minCostPath } + +// Example + +// minCostPath([ +// [2, 1], +// [3, 1], +// [4, 2] +// ]) -main() +// minCostPath([ +// [2, 1, 4], +// [2, 1, 3], +// [3, 2, 1] +// ]) diff --git a/Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js b/Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js index f45d069858..7ae79e12aa 100644 --- a/Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js +++ b/Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js @@ -23,10 +23,10 @@ function NumberOfSubsetSum (array, sum) { return dp[sum] } -function main () { - const array = [1, 1, 2, 2, 3, 1, 1] - const sum = 4 - const result = NumberOfSubsetSum(array, sum) - console.log(result) -} -main() +// example + +// const array = [1, 1, 2, 2, 3, 1, 1] +// const sum = 4 +// const result = NumberOfSubsetSum(array, sum) + +export { NumberOfSubsetSum } diff --git a/Dynamic-Programming/Shuf.js b/Dynamic-Programming/Shuf.js index a6767c9a61..cb064097fb 100644 --- a/Dynamic-Programming/Shuf.js +++ b/Dynamic-Programming/Shuf.js @@ -76,21 +76,21 @@ function randomizeOutputFromDataset (datasetSource, output) { return newOutput } -const main = () => { - /** - * Generates a random range of data, with values between 0 and 2^31 - 1 - * @param {number} length The number of data items to generate - * @returns {Iterable} Random iterable data - */ - function * generateRandomData (length) { - const maxValue = Math.pow(2, 31) - 1 - for (let i = 0; i < length; i++) { - yield Math.floor(Math.random() * maxValue) - } - } +// Example - const source = generateRandomData(1000) - const result = shuf(source, 10) - console.log(result) +/** + * Generates a random range of data, with values between 0 and 2^31 - 1 + * @param {number} length The number of data items to generate + * @returns {Iterable} Random iterable data +*/ +function * generateRandomData (length) { + const maxValue = Math.pow(2, 31) - 1 + for (let i = 0; i < length; i++) { + yield Math.floor(Math.random() * maxValue) + } } -main() + +// const source = generateRandomData(1000) +// const result = shuf(source, 10) + +export { shuf, generateRandomData } diff --git a/Dynamic-Programming/SieveOfEratosthenes.js b/Dynamic-Programming/SieveOfEratosthenes.js index b6b71a1959..2203e3fd7f 100644 --- a/Dynamic-Programming/SieveOfEratosthenes.js +++ b/Dynamic-Programming/SieveOfEratosthenes.js @@ -18,14 +18,9 @@ function sieveOfEratosthenes (n) { return primes } -function main () { - const n = 69 // number till where we wish to find primes - const primes = sieveOfEratosthenes(n) - for (let i = 2; i <= n; i++) { - if (primes[i]) { - console.log(i) - } - } -} +// Example + +// const n = 69 // number till where we wish to find primes +// const primes = sieveOfEratosthenes(n) -main() +export { sieveOfEratosthenes } diff --git a/Dynamic-Programming/SudokuSolver.js b/Dynamic-Programming/SudokuSolver.js index 23e9135361..d2549eb9a9 100644 --- a/Dynamic-Programming/SudokuSolver.js +++ b/Dynamic-Programming/SudokuSolver.js @@ -1,14 +1,3 @@ -const _board = [ - ['.', '9', '.', '.', '4', '2', '1', '3', '6'], - ['.', '.', '.', '9', '6', '.', '4', '8', '5'], - ['.', '.', '.', '5', '8', '1', '.', '.', '.'], - ['.', '.', '4', '.', '.', '.', '.', '.', '.'], - ['5', '1', '7', '2', '.', '.', '9', '.', '.'], - ['6', '.', '2', '.', '.', '.', '3', '7', '.'], - ['1', '.', '.', '8', '.', '4', '.', '2', '.'], - ['7', '.', '6', '.', '.', '.', '8', '1', '.'], - ['3', '.', '.', '.', '9', '.', '.', '.', '.'] -] const isValid = (board, row, col, k) => { for (let i = 0; i < 9; i++) { @@ -43,8 +32,18 @@ const sudokuSolver = (data) => { } // testing -(() => { - if (sudokuSolver(_board)) { - console.log(_board) - } -})() + +// const board = [ +// ['.', '9', '.', '.', '4', '2', '1', '3', '6'], +// ['.', '.', '.', '9', '6', '.', '4', '8', '5'], +// ['.', '.', '.', '5', '8', '1', '.', '.', '.'], +// ['.', '.', '4', '.', '.', '.', '.', '.', '.'], +// ['5', '1', '7', '2', '.', '.', '9', '.', '.'], +// ['6', '.', '2', '.', '.', '.', '3', '7', '.'], +// ['1', '.', '.', '8', '.', '4', '.', '2', '.'], +// ['7', '.', '6', '.', '.', '.', '8', '1', '.'], +// ['3', '.', '.', '.', '9', '.', '.', '.', '.'] +// ] +// sudokuSolver(board) // -> board updated by reference + +export { sudokuSolver } diff --git a/Dynamic-Programming/ZeroOneKnapsack.js b/Dynamic-Programming/ZeroOneKnapsack.js index f3c47135fc..4a9bbfa118 100644 --- a/Dynamic-Programming/ZeroOneKnapsack.js +++ b/Dynamic-Programming/ZeroOneKnapsack.js @@ -20,7 +20,7 @@ const zeroOneKnapsack = (arr, n, cap, cache) => { } } -const main = () => { +const example = () => { /* Problem Statement: You are a thief carrying a single bag with limited capacity S. The museum you stole had N artifact that you could steal. Unfortunately you might not be able to steal all the artifact because of your limited bag capacity. @@ -40,6 +40,8 @@ const main = () => { input.shift() const length = input.length + const output = [] + let i = 0 while (i < length) { const cap = Number(input[i].trim().split(' ')[0]) @@ -62,9 +64,11 @@ const main = () => { cache.push(temp) } const result = zeroOneKnapsack(newArr, currlen, cap, cache) - console.log(result) + output.push(result) i += currlen + 1 } + + return output } -main() +export { zeroOneKnapsack, example } diff --git a/Geometry/ConvexHullGraham.js b/Geometry/ConvexHullGraham.js index 756121fb5a..e74b226eb7 100644 --- a/Geometry/ConvexHullGraham.js +++ b/Geometry/ConvexHullGraham.js @@ -2,7 +2,8 @@ * Author: Arnab Ray * ConvexHull using Graham Scan * Wikipedia: https://en.wikipedia.org/wiki/Graham_scan - * Given a set of points in the plane. The Convex hull of the set is the smallest convex polygon that contains all the points of it. + * Given a set of points in the plane. The Convex hull of the set is the smallest + * convex polygon that contains all the points of it. */ function compare (a, b) { @@ -27,7 +28,7 @@ function orientation (a, b, c) { function convexHull (points) { const pointsLen = points.length if (pointsLen <= 2) { - console.log('Minimum of 3 points is required to form closed polygon!') + throw new Error('Minimum of 3 points is required to form closed polygon!') } points.sort(compare) @@ -65,18 +66,22 @@ function convexHull (points) { for (let i = lowerPoints.length - 1; i >= 0; i--) { hull.push(lowerPoints[i]) } - console.log('The Convex Hull found is: \n') - console.log(hull) + + return hull } -const points = [ - { x: 0, y: 3 }, - { x: 1, y: 1 }, - { x: 2, y: 2 }, - { x: 4, y: 4 }, - { x: 0, y: 0 }, - { x: 1, y: 2 }, - { x: 3, y: 1 }, - { x: 3, y: 3 }] +export { convexHull } + +// Example + +// const points = [ +// { x: 0, y: 3 }, +// { x: 1, y: 1 }, +// { x: 2, y: 2 }, +// { x: 4, y: 4 }, +// { x: 0, y: 0 }, +// { x: 1, y: 2 }, +// { x: 3, y: 1 }, +// { x: 3, y: 3 }] -convexHull(points) +// convexHull(points) diff --git a/Graphs/ConnectedComponents.js b/Graphs/ConnectedComponents.js index 842a2eedcb..1fb74068e7 100644 --- a/Graphs/ConnectedComponents.js +++ b/Graphs/ConnectedComponents.js @@ -45,12 +45,12 @@ class GraphUnweightedUndirectedAdjacencyList { } } -function main () { - const graph = new GraphUnweightedUndirectedAdjacencyList() - graph.addEdge(1, 2) // Component 1 - graph.addEdge(3, 4) // Component 2 - graph.addEdge(3, 5) // Component 2 - console.log(graph.connectedComponents()) -} +export { GraphUnweightedUndirectedAdjacencyList } + +// Example -main() +// const graph = new GraphUnweightedUndirectedAdjacencyList() +// graph.addEdge(1, 2) // Component 1 +// graph.addEdge(3, 4) // Component 2 +// graph.addEdge(3, 5) // Component 2 +// const components = graph.connectedComponents() diff --git a/Graphs/Density.js b/Graphs/Density.js index 116fb8e401..6659287c71 100644 --- a/Graphs/Density.js +++ b/Graphs/Density.js @@ -8,4 +8,4 @@ function density (numberOfNodes, numberOfEdges, isDirected = false) { return (multi * numberOfEdges) / (numberOfNodes * (numberOfNodes - 1)) } -console.log(density(10, 2)) +export { density } diff --git a/Graphs/DepthFirstSearchIterative.js b/Graphs/DepthFirstSearchIterative.js index 3eb9c1f832..cf2db373d0 100644 --- a/Graphs/DepthFirstSearchIterative.js +++ b/Graphs/DepthFirstSearchIterative.js @@ -38,14 +38,14 @@ class GraphUnweightedUndirected { } } -function main () { - const graph = new GraphUnweightedUndirected() - graph.addEdge(1, 2) - graph.addEdge(2, 3) - graph.addEdge(2, 4) - graph.addEdge(3, 5) - console.log(graph.DFSIterative(5, 1)) - console.log(graph.DFSIterative(5, 100)) -} +export { GraphUnweightedUndirected } + +// Example -main() +// const graph = new GraphUnweightedUndirected() +// graph.addEdge(1, 2) +// graph.addEdge(2, 3) +// graph.addEdge(2, 4) +// graph.addEdge(3, 5) +// graph.DFSIterative(5, 1) +// graph.DFSIterative(5, 100) diff --git a/Graphs/DepthFirstSearchRecursive.js b/Graphs/DepthFirstSearchRecursive.js index 6522e9d15f..4737590357 100644 --- a/Graphs/DepthFirstSearchRecursive.js +++ b/Graphs/DepthFirstSearchRecursive.js @@ -33,14 +33,12 @@ class GraphUnweightedUndirected { } } -function main () { - const graph = new GraphUnweightedUndirected() - graph.addEdge(1, 2) - graph.addEdge(2, 3) - graph.addEdge(2, 4) - graph.addEdge(3, 5) - console.log(graph.DFSRecursive(5, 1)) - console.log(graph.DFSRecursive(5, 100)) -} +export { GraphUnweightedUndirected } -main() +// const graph = new GraphUnweightedUndirected() +// graph.addEdge(1, 2) +// graph.addEdge(2, 3) +// graph.addEdge(2, 4) +// graph.addEdge(3, 5) +// graph.DFSRecursive(5, 1) +// graph.DFSRecursive(5, 100) diff --git a/Graphs/Dijkstra.js b/Graphs/Dijkstra.js index 41bacd71dc..5271c6f70d 100644 --- a/Graphs/Dijkstra.js +++ b/Graphs/Dijkstra.js @@ -47,30 +47,30 @@ function djikstra (graph, V, src) { return dist } -const V = 9 -const E = [ - [0, 1, 4], - [0, 7, 8], - [1, 7, 11], - [1, 2, 8], - [7, 8, 7], - [6, 7, 1], - [2, 8, 2], - [6, 8, 6], - [5, 6, 2], - [2, 5, 4], - [2, 3, 7], - [3, 5, 14], - [3, 4, 9], - [4, 5, 10] -] +export { createGraph, djikstra } -const graph = createGraph(V, E) -const distances = djikstra(graph, V, 0) +// const V = 9 +// const E = [ +// [0, 1, 4], +// [0, 7, 8], +// [1, 7, 11], +// [1, 2, 8], +// [7, 8, 7], +// [6, 7, 1], +// [2, 8, 2], +// [6, 8, 6], +// [5, 6, 2], +// [2, 5, 4], +// [2, 3, 7], +// [3, 5, 14], +// [3, 4, 9], +// [4, 5, 10] +// ] + +// const graph = createGraph(V, E) +// const distances = djikstra(graph, V, 0) /** * The first value in the array determines the minimum distance and the * second value represents the parent node from which the minimum distance has been calculated */ - -console.log(distances) diff --git a/Graphs/DijkstraSmallestPath.js b/Graphs/DijkstraSmallestPath.js index 9e36836ff5..81ee9767f3 100644 --- a/Graphs/DijkstraSmallestPath.js +++ b/Graphs/DijkstraSmallestPath.js @@ -39,28 +39,31 @@ function solve (graph, s) { return solutions } -// create graph -const graph = {} -const layout = { - R: ['2'], - 2: ['3', '4'], - 3: ['4', '6', '13'], - 4: ['5', '8'], - 5: ['7', '11'], - 6: ['13', '15'], - 7: ['10'], - 8: ['11', '13'], - 9: ['14'], - 10: [], - 11: ['12'], - 12: [], - 13: ['14'], - 14: [], - 15: [] -} +export { solve } + +// // create graph +// const graph = {} + +// const layout = { +// R: ['2'], +// 2: ['3', '4'], +// 3: ['4', '6', '13'], +// 4: ['5', '8'], +// 5: ['7', '11'], +// 6: ['13', '15'], +// 7: ['10'], +// 8: ['11', '13'], +// 9: ['14'], +// 10: [], +// 11: ['12'], +// 12: [], +// 13: ['14'], +// 14: [], +// 15: [] +// } -// convert uni-directional to bi-directional graph +// // convert uni-directional to bi-directional graph // let graph = { // a: {e:1, b:1, g:3}, // b: {a:1, c:1}, @@ -72,26 +75,22 @@ const layout = { // h: {f:1} // }; -for (const id in layout) { - if (!graph[id]) { graph[id] = {} } - layout[id].forEach(function (aid) { - graph[id][aid] = 1 - if (!graph[aid]) { graph[aid] = {} } - graph[aid][id] = 1 - }) -} +// for (const id in layout) { +// if (!graph[id]) { graph[id] = {} } +// layout[id].forEach(function (aid) { +// graph[id][aid] = 1 +// if (!graph[aid]) { graph[aid] = {} } +// graph[aid][id] = 1 +// }) +// } -// choose start node -const start = '10' -// get all solutions -const solutions = solve(graph, start) +// // choose start node +// const start = '10' +// // get all solutions +// const solutions = solve(graph, start) -console.log("From '" + start + "' to") -// display solutions -for (const s in solutions) { - if (!solutions[s]) continue - console.log(' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')') -} +// // for s in solutions.. +// ' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')' // From '10' to // -> 2: [7, 5, 4, 2] (dist:4) diff --git a/Graphs/FloydWarshall.js b/Graphs/FloydWarshall.js index 67c41e135c..4552d4c602 100644 --- a/Graphs/FloydWarshall.js +++ b/Graphs/FloydWarshall.js @@ -23,26 +23,25 @@ const FloydWarshall = (dist) => { return dist } -const main = () => { - // For the following graph (edge weights are shown in brackets) - // 4 1 dist[1][2] = dist[2][1] = 1 - // \ (2)/ \ dist[1][3] = dist[3][1] = 2 - // \ / \(1) dist[1][4] = dist[4][1] = Infinity - // (1)\ / \ dist[3][4] = dist[4][3] = 1 - // 3 2 dist[2][4] = dist[4][2] = Infinity - // dist[2][3] = dist[3][2] = Infinity - // Output should be: - // [ [0, 1, 2, 3], - // [1, 0, 3, 4], - // [2, 3, 0, 1], - // [3, 4, 1, 0] ] - console.log(FloydWarshall( - [[0, 1, 2, Infinity], - [1, 0, Infinity, Infinity], - [2, Infinity, 0, 1], - [Infinity, Infinity, 1, 0] - ] - )) -} +export { FloydWarshall } + +// For the following graph (edge weights are shown in brackets) +// 4 1 dist[1][2] = dist[2][1] = 1 +// \ (2)/ \ dist[1][3] = dist[3][1] = 2 +// \ / \(1) dist[1][4] = dist[4][1] = Infinity +// (1)\ / \ dist[3][4] = dist[4][3] = 1 +// 3 2 dist[2][4] = dist[4][2] = Infinity +// dist[2][3] = dist[3][2] = Infinity +// Output should be: +// [ [0, 1, 2, 3], +// [1, 0, 3, 4], +// [2, 3, 0, 1], +// [3, 4, 1, 0] ] -main() +// FloydWarshall( +// [[0, 1, 2, Infinity], +// [1, 0, Infinity, Infinity], +// [2, Infinity, 0, 1], +// [Infinity, Infinity, 1, 0] +// ] +// ) diff --git a/Graphs/KruskalMST.js b/Graphs/KruskalMST.js index 0a09c631ba..7fe55d460c 100644 --- a/Graphs/KruskalMST.js +++ b/Graphs/KruskalMST.js @@ -101,15 +101,12 @@ class GraphWeightedUndirectedAdjacencyList { } } -function main () { - const graph = new GraphWeightedUndirectedAdjacencyList() - graph.addEdge(1, 2, 1) - graph.addEdge(2, 3, 2) - graph.addEdge(3, 4, 1) - graph.addEdge(3, 5, 100) // Removed in MST - graph.addEdge(4, 5, 5) - console.log(graph) - console.log(graph.KruskalMST()) -} +export { GraphWeightedUndirectedAdjacencyList } -main() +// const graph = new GraphWeightedUndirectedAdjacencyList() +// graph.addEdge(1, 2, 1) +// graph.addEdge(2, 3, 2) +// graph.addEdge(3, 4, 1) +// graph.addEdge(3, 5, 100) // Removed in MST +// graph.addEdge(4, 5, 5) +// graph.KruskalMST() diff --git a/Graphs/NodeNeighbors.js b/Graphs/NodeNeighbors.js index c22b9905a7..65f125b18b 100644 --- a/Graphs/NodeNeighbors.js +++ b/Graphs/NodeNeighbors.js @@ -30,11 +30,11 @@ class Graph { } } -(() => { - const graph = new Graph() - graph.addEdge(1, 2) - graph.addEdge(2, 3) - graph.addEdge(3, 5) - graph.addEdge(1, 5) - console.log(graph.nodeNeighbors(1)) -})() +export { Graph } + +// const graph = new Graph() +// graph.addEdge(1, 2) +// graph.addEdge(2, 3) +// graph.addEdge(3, 5) +// graph.addEdge(1, 5) +// graph.nodeNeighbors(1) diff --git a/Graphs/NumberOfIslands.js b/Graphs/NumberOfIslands.js index 51a447dd09..84b666d373 100644 --- a/Graphs/NumberOfIslands.js +++ b/Graphs/NumberOfIslands.js @@ -46,12 +46,6 @@ Pseudocode: Return the count */ -const grid = [ - ['1', '1', '0', '0', '0'], - ['1', '1', '0', '0', '0'], - ['0', '0', '1', '0', '0'], - ['0', '0', '0', '1', '1'] -] const islands = (matrixGrid) => { const matrix = matrixGrid @@ -83,4 +77,12 @@ const islands = (matrixGrid) => { } return counter } -console.log(islands(grid)) + +export { islands } + +// islands( +// ['1', '1', '0', '0', '0'], +// ['1', '1', '0', '0', '0'], +// ['0', '0', '1', '0', '0'], +// ['0', '0', '0', '1', '1'] +// ) diff --git a/Graphs/PrimMST.js b/Graphs/PrimMST.js index be1e18c0d0..17d68efb90 100644 --- a/Graphs/PrimMST.js +++ b/Graphs/PrimMST.js @@ -197,14 +197,12 @@ class GraphWeightedUndirectedAdjacencyList { } } -function main () { - const graph = new GraphWeightedUndirectedAdjacencyList() - graph.addEdge(1, 2, 1) - graph.addEdge(2, 3, 2) - graph.addEdge(3, 4, 1) - graph.addEdge(3, 5, 100) // Removed in MST - graph.addEdge(4, 5, 5) - console.log(graph.PrimMST(1)) -} - -main() +export { GraphWeightedUndirectedAdjacencyList } + +// const graph = new GraphWeightedUndirectedAdjacencyList() +// graph.addEdge(1, 2, 1) +// graph.addEdge(2, 3, 2) +// graph.addEdge(3, 4, 1) +// graph.addEdge(3, 5, 100) // Removed in MST +// graph.addEdge(4, 5, 5) +// graph.PrimMST(1) diff --git a/Hashes/SHA1.js b/Hashes/SHA1.js index 864ca392a8..98cb03a444 100644 --- a/Hashes/SHA1.js +++ b/Hashes/SHA1.js @@ -170,8 +170,5 @@ function SHA1 (message) { return HH } -console.log(SHA1('A Test')) -console.log(SHA1('A Test')) - // export SHA1 function -module.exports = SHA1 +export { SHA1 } diff --git a/Hashes/SHA256.js b/Hashes/SHA256.js index d47dfb03ee..61841e2abf 100644 --- a/Hashes/SHA256.js +++ b/Hashes/SHA256.js @@ -185,4 +185,4 @@ function SHA256 (message) { } // export SHA256 function -module.exports = SHA256 +export { SHA256 } diff --git a/Linear-Algebra/test/test.js b/Linear-Algebra/test/test.js index 1deb0f8b29..a99d97aad9 100644 --- a/Linear-Algebra/test/test.js +++ b/Linear-Algebra/test/test.js @@ -5,12 +5,11 @@ This file contains the test-suite for the linear algebra library. The tests use javascript test-framework mocha */ -/* eslint-disable */ -import { LinearAlgebra } from "../src/la_lib" +/* eslint-disable */ -var assert = require('assert') -var fs = require('fs') +import { LinearAlgebra } from '../src/la_lib' +import * as assert from 'assert' // file is included here // Tests goes here @@ -211,4 +210,4 @@ describe('class Matrix', function () { assert.ok(B.equal(C)) }) }) -}) \ No newline at end of file +}) diff --git a/Maths/CheckKishnamurthyNumber.js b/Maths/CheckKishnamurthyNumber.js index d030fff846..2a1f979d5a 100644 --- a/Maths/CheckKishnamurthyNumber.js +++ b/Maths/CheckKishnamurthyNumber.js @@ -41,4 +41,4 @@ const CheckKishnamurthyNumber = (number) => { return sumOfAllDigitFactorial === number } -module.exports = CheckKishnamurthyNumber +export { CheckKishnamurthyNumber } diff --git a/Maths/CoPrimeCheck.js b/Maths/CoPrimeCheck.js index 11aa7b89b9..d4a463a903 100644 --- a/Maths/CoPrimeCheck.js +++ b/Maths/CoPrimeCheck.js @@ -37,4 +37,4 @@ const CoPrimeCheck = (firstNumber, secondNumber) => { return GetEuclidGCD(firstNumber, secondNumber) === 1 } -module.exports = CoPrimeCheck +export { CoPrimeCheck } diff --git a/Maths/GetEuclidGCD.js b/Maths/GetEuclidGCD.js index 5eb51597b7..3aff8dbbeb 100644 --- a/Maths/GetEuclidGCD.js +++ b/Maths/GetEuclidGCD.js @@ -29,4 +29,4 @@ const GetEuclidGCD = (arg1, arg2) => { return (less) } -module.exports = GetEuclidGCD +export { GetEuclidGCD } diff --git a/Maths/IsDivisible.js b/Maths/IsDivisible.js index 9c2ec81cf5..2d9083c561 100644 --- a/Maths/IsDivisible.js +++ b/Maths/IsDivisible.js @@ -10,6 +10,6 @@ export const isDivisible = (num1, num2) => { return num1 % num2 === 0 } -console.log(isDivisible(10, 5)) // returns true -console.log(isDivisible(123498175, 5)) // returns true -console.log(isDivisible(99, 5)) // returns false +// isDivisible(10, 5) // returns true +// isDivisible(123498175, 5) // returns true +// isDivisible(99, 5) // returns false diff --git a/Maths/MatrixExponentiationRecursive.js b/Maths/MatrixExponentiationRecursive.js index 6ee00aa250..b672e69bb0 100644 --- a/Maths/MatrixExponentiationRecursive.js +++ b/Maths/MatrixExponentiationRecursive.js @@ -45,7 +45,7 @@ const MatMult = (matA, matB) => { return matC } -const MatrixExponentiationRecursive = (mat, m) => { +export const MatrixExponentiationRecursive = (mat, m) => { // Input: mat: 2D Array of Numbers of size n x n // Output: mat^n: 2D Array of Numbers of size n x n // Complexity: O(n^3 log m) @@ -65,20 +65,16 @@ const MatrixExponentiationRecursive = (mat, m) => { } } -const main = () => { - const mat = [[1, 0, 2], [2, 1, 0], [0, 2, 1]] +// const mat = [[1, 0, 2], [2, 1, 0], [0, 2, 1]] - // mat ^ 0 = [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ] - console.log(MatrixExponentiationRecursive(mat, 0)) +// // mat ^ 0 = [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ] +// MatrixExponentiationRecursive(mat, 0) - // mat ^ 1 = [ [ 1, 0, 2 ], [ 2, 1, 0 ], [ 0, 2, 1 ] ] - console.log(MatrixExponentiationRecursive(mat, 1)) +// // mat ^ 1 = [ [ 1, 0, 2 ], [ 2, 1, 0 ], [ 0, 2, 1 ] ] +// MatrixExponentiationRecursive(mat, 1) - // mat ^ 2 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ] - console.log(MatrixExponentiationRecursive(mat, 2)) +// // mat ^ 2 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ] +// MatrixExponentiationRecursive(mat, 2) - // mat ^ 5 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ] - console.log(MatrixExponentiationRecursive(mat, 5)) -} - -main() +// // mat ^ 5 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ] +// MatrixExponentiationRecursive(mat, 5) diff --git a/Maths/MatrixMultiplication.js b/Maths/MatrixMultiplication.js index 306c689f6b..9fc2a924bc 100644 --- a/Maths/MatrixMultiplication.js +++ b/Maths/MatrixMultiplication.js @@ -10,7 +10,7 @@ const matrixCheck = (matrix) => { if (index === 0) { columnNumb = matrix[index].length } else if (matrix[index].length !== columnNumb) { - console.log('The columns in this array are not equal') + // The columns in this array are not equal } else { return columnNumb } @@ -21,7 +21,7 @@ const matrixCheck = (matrix) => { const twoMatricesCheck = (first, second) => { const [firstRowLength, secondRowLength, firstColLength, secondColLength] = [first.length, second.length, matrixCheck(first), matrixCheck(second)] if (firstRowLength !== secondColLength || secondRowLength !== firstColLength) { - console.log('These matrices do not have a common side') + // These matrices do not have a common side return false } else { return true @@ -44,7 +44,7 @@ const initiateEmptyArray = (first, second) => { // Finally, `matrixMult` uses `Array.prototype.push()`, multiple layers of nested `for` loops, the addition assignment `+=` operator and multiplication operator `*` to perform the dot product between two matrices of differing sizes. // Dot product, takes the row of the first matrix and multiplies it by the column of the second matrix, the `twoMatricesCheck` tested to see if they were the same size already. // The dot product for each iteration is then saved to its respective index into `multMatrix`. -const matrixMult = (firstArray, secondArray) => { +export const matrixMult = (firstArray, secondArray) => { const multMatrix = initiateEmptyArray(firstArray, secondArray) for (let rm = 0; rm < firstArray.length; rm++) { const rowMult = [] @@ -66,26 +66,26 @@ const matrixMult = (firstArray, secondArray) => { return multMatrix } -const firstMatrix = [ - [1, 2], - [3, 4] -] +// const firstMatrix = [ +// [1, 2], +// [3, 4] +// ] -const secondMatrix = [ - [5, 6], - [7, 8] -] +// const secondMatrix = [ +// [5, 6], +// [7, 8] +// ] -console.log(matrixMult(firstMatrix, secondMatrix)) // [ [ 19, 22 ], [ 43, 50 ] ] +// matrixMult(firstMatrix, secondMatrix) // [ [ 19, 22 ], [ 43, 50 ] ] -const thirdMatrix = [ - [-1, 4, 1], - [7, -6, 2] -] -const fourthMatrix = [ - [2, -2], - [5, 3], - [3, 2] -] +// const thirdMatrix = [ +// [-1, 4, 1], +// [7, -6, 2] +// ] +// const fourthMatrix = [ +// [2, -2], +// [5, 3], +// [3, 2] +// ] -console.log(matrixMult(thirdMatrix, fourthMatrix)) // [ [ 21, 16 ], [ -10, -28 ] ] +// matrixMult(thirdMatrix, fourthMatrix) // [ [ 21, 16 ], [ -10, -28 ] ] diff --git a/Maths/PermutationAndCombination.js b/Maths/PermutationAndCombination.js index 1146230fb7..ba99888ce0 100644 --- a/Maths/PermutationAndCombination.js +++ b/Maths/PermutationAndCombination.js @@ -47,21 +47,4 @@ const combination = (n, r) => { } // Exports the functions to be used in other files. -module.exports.factorial = factorial -module.exports.permutation = permutation -module.exports.combination = combination - -/** - * @example - - const funcs = require("./PermutationAndCombination.js"); - - console.log(funcs.factorial(5)); - console.log(funcs.permutation(5, 2)); - console.log(funcs.combination(5, 2)); - - * @output - 120 - 20 - 10 - */ +export { factorial, permutation, combination } diff --git a/Maths/ReverseNumber.js b/Maths/ReverseNumber.js index 4995761f3c..2f29903c93 100644 --- a/Maths/ReverseNumber.js +++ b/Maths/ReverseNumber.js @@ -26,4 +26,4 @@ const ReverseNumber = (number) => { return reverseNumber } -module.exports = ReverseNumber +export { ReverseNumber } diff --git a/Maths/WhileLoopFactorial.js b/Maths/WhileLoopFactorial.js index 58501697f6..7e04bbafa1 100644 --- a/Maths/WhileLoopFactorial.js +++ b/Maths/WhileLoopFactorial.js @@ -1,7 +1,7 @@ /* author: Theepag */ -const factorialize = (num) => { +export const factorialize = (num) => { // Step 1. variable result to store num let result = num // If num = 0 OR 1, the factorial will return 1 @@ -14,6 +14,3 @@ const factorialize = (num) => { // Step 3. Return the factorial return result } -// test -console.log(factorialize(5)) -console.log(factorialize(4)) diff --git a/Maths/decimalIsolate.js b/Maths/decimalIsolate.js index aae6e8ed7c..06a29fb8ef 100644 --- a/Maths/decimalIsolate.js +++ b/Maths/decimalIsolate.js @@ -4,14 +4,7 @@ * Return the result. */ -const decimalIsolate = (number) => { +export const decimalIsolate = (number) => { const ans = parseFloat((number + '').replace(/^[-\d]+./, '.')) return isNaN(ans) === true ? 0 : ans } - -// testing -console.log(decimalIsolate(35.345)) -console.log(decimalIsolate(56.879)) -console.log(decimalIsolate(89.5643)) -console.log(decimalIsolate(38.00)) -console.log(decimalIsolate(33)) diff --git a/Maths/isOdd.js b/Maths/isOdd.js index fffe17930c..5caeb4a6ba 100644 --- a/Maths/isOdd.js +++ b/Maths/isOdd.js @@ -4,10 +4,6 @@ * else false */ -const isOdd = (value) => { +export const isOdd = (value) => { return !!((value & 1)) } - -// testing -console.log(isOdd(2)) -console.log(isOdd(3)) diff --git a/Maths/test/BinaryExponentiationRecursive.test.js b/Maths/test/BinaryExponentiationRecursive.test.js index 40ad201420..dc48d22d59 100644 --- a/Maths/test/BinaryExponentiationRecursive.test.js +++ b/Maths/test/BinaryExponentiationRecursive.test.js @@ -1,4 +1,4 @@ -const { binaryExponentiation } = require('../BinaryExponentiationRecursive') +import { binaryExponentiation } from '../BinaryExponentiationRecursive' describe('BinaryExponentiationRecursive', () => { it('should calculate 2 to the power of 10 correctly', () => { diff --git a/Maths/test/PermutationAndCombination.test.js b/Maths/test/PermutationAndCombination.test.js new file mode 100644 index 0000000000..92fc576c19 --- /dev/null +++ b/Maths/test/PermutationAndCombination.test.js @@ -0,0 +1,19 @@ +import { factorial, permutation, combination } from '../PermutationAndCombination' + +describe('Factorial', () => { + it('factorial(5)', () => { + expect(factorial(5)).toBe(120) + }) +}) + +describe('Permutation', () => { + it('permutation(5, 2)', () => { + expect(permutation(5, 2)).toBe(20) + }) +}) + +describe('Combination', () => { + it('combination(5, 2)', () => { + expect(combination(5, 2)).toBe(10) + }) +}) diff --git a/Project-Euler/Problem1.js b/Project-Euler/Problem001.js similarity index 61% rename from Project-Euler/Problem1.js rename to Project-Euler/Problem001.js index af3582f030..65a35e32a1 100644 --- a/Project-Euler/Problem1.js +++ b/Project-Euler/Problem001.js @@ -4,8 +4,6 @@ Find the sum of all the multiples of 3 or 5 below the provided parameter value number. */ -const readline = require('readline') - const multiplesThreeAndFive = (num) => { let total = 0 // total for calculating the sum @@ -17,11 +15,4 @@ const multiplesThreeAndFive = (num) => { return total } -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}) -rl.question('Enter a number: ', function (num) { - console.log(multiplesThreeAndFive(num)) // multiples3_5 function to calculate the sum of multiples of 3 and 5 within num - rl.close() -}) +export { multiplesThreeAndFive } diff --git a/Project-Euler/Problem2.js b/Project-Euler/Problem002.js similarity index 82% rename from Project-Euler/Problem2.js rename to Project-Euler/Problem002.js index 35b011206b..5b8c3ddd51 100644 --- a/Project-Euler/Problem2.js +++ b/Project-Euler/Problem002.js @@ -4,10 +4,9 @@ const PHI = (1 + SQ5) / 2 // definition of PHI // theoretically it should take O(1) constant amount of time as long // arithmetic calculations are considered to be in constant amount of time -const EvenFibonacci = (limit) => { +export const EvenFibonacci = (limit) => { const highestIndex = Math.floor(Math.log(limit * SQ5) / Math.log(PHI)) const n = Math.floor(highestIndex / 3) return ((PHI ** (3 * n + 3) - 1) / (PHI ** 3 - 1) - ((1 - PHI) ** (3 * n + 3) - 1) / ((1 - PHI) ** 3 - 1)) / SQ5 } -console.log(EvenFibonacci(4e6)) // Sum of even Fibonacci upto 4 Million diff --git a/Project-Euler/Problem3.js b/Project-Euler/Problem003.js similarity index 77% rename from Project-Euler/Problem3.js rename to Project-Euler/Problem003.js index d870b80b46..789f622065 100644 --- a/Project-Euler/Problem3.js +++ b/Project-Euler/Problem003.js @@ -1,7 +1,6 @@ // https://projecteuler.net/problem=3 -const problem = 600851475143 -const largestPrime = (num) => { +export const largestPrime = (num = 600851475143) => { let newnumm = num let largestFact = 0 let counter = 2 @@ -17,4 +16,3 @@ const largestPrime = (num) => { } return largestFact } -console.log(largestPrime(problem)) diff --git a/Project-Euler/Problem4.js b/Project-Euler/Problem004.js similarity index 93% rename from Project-Euler/Problem4.js rename to Project-Euler/Problem004.js index bcc4d880b6..34fa87471d 100644 --- a/Project-Euler/Problem4.js +++ b/Project-Euler/Problem004.js @@ -2,7 +2,7 @@ /* 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. */ -const largestPalindromic = (digits) => { +export const largestPalindromic = (digits) => { let i let n let m @@ -42,5 +42,3 @@ const largestPalindromic = (digits) => { } return NaN // returning not a number, if any such case arise } - -console.log(largestPalindromic(3)) diff --git a/Project-Euler/Problem5.js b/Project-Euler/Problem005.js similarity index 87% rename from Project-Euler/Problem5.js rename to Project-Euler/Problem005.js index 0ba30669a5..9b0020a754 100644 --- a/Project-Euler/Problem5.js +++ b/Project-Euler/Problem005.js @@ -5,7 +5,7 @@ Smallest multiple What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? */ -const findSmallestMultiple = () => { +export const findSmallestMultiple = () => { const divisors = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2] let num = 21 let result @@ -18,5 +18,3 @@ const findSmallestMultiple = () => { return result } - -console.log(findSmallestMultiple()) diff --git a/Project-Euler/Problem6.js b/Project-Euler/Problem006.js similarity index 68% rename from Project-Euler/Problem6.js rename to Project-Euler/Problem006.js index 38dd31d950..673202acf7 100644 --- a/Project-Euler/Problem6.js +++ b/Project-Euler/Problem006.js @@ -1,8 +1,6 @@ // https://projecteuler.net/problem=6 -const num = 100 // number we are checking; change to 10 to check 10 from example - -const squareDifference = (num) => { +export const squareDifference = (num = 100) => { let sumOfSquares = 0 let sums = 0 for (let i = 1; i <= num; i++) { @@ -11,5 +9,3 @@ const squareDifference = (num) => { } return (sums ** 2) - sumOfSquares // difference of square of the total sum and sum of squares } - -console.log(squareDifference(num)) diff --git a/Project-Euler/Problem7.js b/Project-Euler/Problem007.js similarity index 85% rename from Project-Euler/Problem7.js rename to Project-Euler/Problem007.js index debc75276b..2bb4eeef44 100644 --- a/Project-Euler/Problem7.js +++ b/Project-Euler/Problem007.js @@ -1,10 +1,7 @@ // https://projecteuler.net/problem=7 // My approach does not use the Sieve of Eratosthenes but that is another common way to approach this problem. Sieve of Atkin is another possibility as well. -const num = 10001 -const primes = [2, 3, 5, 7, 11, 13] // given list of primes you start with - -const calculatePrime = (num) => { +export const calculatePrime = (num = 10001, primes = [2, 3, 5, 7, 11, 13]) => { // Calculate each next prime by checking each number to see what it's divisible by let count = primes.length // count number of primes calculated let current = primes[count - 1] + 1 // current number being assessed if prime @@ -27,5 +24,3 @@ const calculatePrime = (num) => { } return primes[num - 1] } - -console.log(calculatePrime(num)) diff --git a/Project-Euler/Problem8.js b/Project-Euler/Problem008.js similarity index 100% rename from Project-Euler/Problem8.js rename to Project-Euler/Problem008.js diff --git a/Project-Euler/Problem9.js b/Project-Euler/Problem009.js similarity index 86% rename from Project-Euler/Problem9.js rename to Project-Euler/Problem009.js index a877c89d86..60422f89e5 100644 --- a/Project-Euler/Problem9.js +++ b/Project-Euler/Problem009.js @@ -12,7 +12,7 @@ Find the product abc. const isPythagoreanTriplet = (a, b, c) => Math.pow(a, 2) + Math.pow(b, 2) === Math.pow(c, 2) -const findSpecialPythagoreanTriplet = () => { +export const findSpecialPythagoreanTriplet = () => { for (let a = 0; a < 1000; a++) { for (let b = a + 1; b < 1000; b++) { for (let c = b + 1; c < 1000; c++) { @@ -23,5 +23,3 @@ const findSpecialPythagoreanTriplet = () => { } } } - -console.log(findSpecialPythagoreanTriplet()) diff --git a/Project-Euler/Problem10.js b/Project-Euler/Problem010.js similarity index 100% rename from Project-Euler/Problem10.js rename to Project-Euler/Problem010.js diff --git a/Project-Euler/Problem013.js b/Project-Euler/Problem013.js index 26769ab9a3..01563186c4 100644 --- a/Project-Euler/Problem013.js +++ b/Project-Euler/Problem013.js @@ -107,13 +107,11 @@ const numbers = [ 53503534226472524250874054075591789781264330331690 ] -const findFirstTenDigitsOfSum = () => { - const sum = numbers.reduce((prev, current) => { +export const findFirstTenDigitsOfSum = (N = numbers) => { + const sum = N.reduce((prev, current) => { current += prev return current }, 0) return sum.toLocaleString('fullwide', { useGrouping: false }).split('').slice(0, 10).join('') } - -console.log(findFirstTenDigitsOfSum()) diff --git a/Project-Euler/Problem014.js b/Project-Euler/Problem014.js index 0331837d09..d2d53fcfab 100644 --- a/Project-Euler/Problem014.js +++ b/Project-Euler/Problem014.js @@ -31,10 +31,10 @@ const getCollatzSequenceLength = (num, seqLength) => { } } -const findLongestCollatzSequence = () => { +export const findLongestCollatzSequence = (limit = 1000000) => { let startingPointForLargestSequence = 1 let largestSequenceLength = 1 - for (let i = 2; i < 1000000; i++) { + for (let i = 2; i < limit; i++) { const currentSequenceLength = getCollatzSequenceLength(i, 1) if (currentSequenceLength > largestSequenceLength) { startingPointForLargestSequence = i @@ -43,5 +43,3 @@ const findLongestCollatzSequence = () => { } return startingPointForLargestSequence } - -console.log(findLongestCollatzSequence()) diff --git a/Project-Euler/Problem015.js b/Project-Euler/Problem015.js index d354047330..1861376244 100644 --- a/Project-Euler/Problem015.js +++ b/Project-Euler/Problem015.js @@ -6,7 +6,7 @@ How many such routes are there through a 20×20 grid? // A lattice path is composed of horizontal and vertical lines that pass through lattice points. -const latticePath = (gridSize) => { +export const latticePath = (gridSize) => { let paths for (let i = 1, paths = 1; i <= gridSize; i++) { paths = paths * (gridSize + i) / i @@ -14,4 +14,6 @@ const latticePath = (gridSize) => { // The total number of paths can be found using the binomial coefficient (b+a)/a. return paths } -console.log(latticePath(20)) // output = 137846528820 + +// > latticePath(20)) +// 137846528820 diff --git a/Project-Euler/test/Problem8.test.js b/Project-Euler/test/Problem008.test.js similarity index 98% rename from Project-Euler/test/Problem8.test.js rename to Project-Euler/test/Problem008.test.js index 3fbb0d5ad4..b9d27324c0 100644 --- a/Project-Euler/test/Problem8.test.js +++ b/Project-Euler/test/Problem008.test.js @@ -1,4 +1,4 @@ -import { largestAdjacentNumber } from '../Problem8' +import { largestAdjacentNumber } from '../Problem008' const grid1 = `73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 diff --git a/Project-Euler/test/Problem10.test.js b/Project-Euler/test/Problem010.test.js similarity index 89% rename from Project-Euler/test/Problem10.test.js rename to Project-Euler/test/Problem010.test.js index 2c1545cd10..da551e4fa9 100644 --- a/Project-Euler/test/Problem10.test.js +++ b/Project-Euler/test/Problem010.test.js @@ -1,4 +1,4 @@ -import { calculateSumOfPrimeNumbers } from '../Problem10' +import { calculateSumOfPrimeNumbers } from '../Problem010' describe('checkAnagram', () => { it('Return the sum of prime numbers upto but less than 14', () => { diff --git a/Recursive/BinaryEquivalent.js b/Recursive/BinaryEquivalent.js index a3a8de0c9e..df92f7b3ff 100644 --- a/Recursive/BinaryEquivalent.js +++ b/Recursive/BinaryEquivalent.js @@ -13,14 +13,9 @@ * */ -const binaryEquivalent = (num) => { +export const binaryEquivalent = (num) => { if (num === 0 || num === 1) { return String(num) } return binaryEquivalent(Math.floor(num / 2)) + String(num % 2) } - -// Driver Code -const num = 6 -const ans = binaryEquivalent(num) -console.log(ans) diff --git a/Recursive/BinarySearch.js b/Recursive/BinarySearch.js index 1df6a2dec5..ef24dcba0d 100644 --- a/Recursive/BinarySearch.js +++ b/Recursive/BinarySearch.js @@ -2,7 +2,7 @@ // https://en.wikipedia.org/wiki/Binary_search_algorithm // Search the integer inside the sorted integers array using Binary Search Algorithm -const BinarySearch = (intArr, searchQuery) => { +export const BinarySearch = (intArr, searchQuery) => { if (searchQuery === null || searchQuery === undefined || intArr.length === 0) { return false } @@ -17,13 +17,3 @@ const BinarySearch = (intArr, searchQuery) => { return false } } - -// testing -(() => { - console.log('Number Present with odd array length: 5 = ', BinarySearch([1, 2, 3, 4, 5, 6, 7], 5)) - console.log('Number Present with even array length: 5 = ', BinarySearch([1, 2, 4, 5, 6], 5)) - console.log('Number Present with only single element: 5 = ', BinarySearch([5], 5)) - console.log('Number Not Present: 0 = ', BinarySearch([1, 2, 3, 4, 5], 0)) - console.log('Undefined number search query = ', BinarySearch([1, 2, 3, 4, 5])) - console.log('With Empty array = ', BinarySearch([], 1)) -})() diff --git a/Recursive/EucledianGCD.js b/Recursive/EucledianGCD.js index 5f1c51a06d..9f4c4a79a0 100644 --- a/Recursive/EucledianGCD.js +++ b/Recursive/EucledianGCD.js @@ -27,11 +27,4 @@ function euclideanGCDIterative (first, second) { return first } -function main () { - const first = 20 - const second = 30 - console.log('Recursive GCD for %d and %d is %d', first, second, euclideanGCDRecursive(first, second)) - console.log('Iterative GCD for %d and %d is %d', first, second, euclideanGCDIterative(first, second)) -} - -main() +export { euclideanGCDIterative, euclideanGCDRecursive } diff --git a/Recursive/FibonacciNumberRecursive.js b/Recursive/FibonacciNumberRecursive.js index e5c5bb95bb..f8d4637495 100644 --- a/Recursive/FibonacciNumberRecursive.js +++ b/Recursive/FibonacciNumberRecursive.js @@ -1,13 +1,15 @@ -// https://en.wikipedia.org/wiki/Fibonacci_number -const fibonacci = (N) => { - if (N === 0 || N === 1) return N +// https://en.wikipedia.org/wiki/Fibonacci_number +/** + * Return the N-th Fibonacci number + * + * @param {number} N + * @returns {number} + */ +export const fibonacci = (N) => { + if (N === 0 || N === 1) { + return N + } return fibonacci(N - 2) + fibonacci(N - 1) } - -// testing -(() => { - const number = 5 - console.log(number + 'th Fibonacci number is ' + fibonacci(number)) -})() diff --git a/Recursive/Palindrome.js b/Recursive/Palindrome.js index 483fb012e2..9357135174 100644 --- a/Recursive/Palindrome.js +++ b/Recursive/Palindrome.js @@ -1,6 +1,6 @@ // Check whether the given string is Palindrome or not -const Palindrome = (str) => { +export const Palindrome = (str) => { if (typeof str !== 'string') { str = str.toString() } @@ -18,13 +18,4 @@ const Palindrome = (str) => { } else { return Palindrome(str.slice(1, str.length - 1)) } -}; - -// testing -(() => { - console.log('Palindrome: String: a = ', Palindrome('a')) - console.log('Palindrome: String: abba = ', Palindrome('abba')) - console.log('Palindrome: String: ababa = ', Palindrome('ababa')) - console.log('Not Palindrome: String: abbxa = ', Palindrome('abbxa')) - console.log('Not Palindrome: String: abxa = ', Palindrome('abxa')) -})() +} diff --git a/Recursive/SubsequenceRecursive.js b/Recursive/SubsequenceRecursive.js index e54798d1b8..c7bedcb7a6 100644 --- a/Recursive/SubsequenceRecursive.js +++ b/Recursive/SubsequenceRecursive.js @@ -19,14 +19,12 @@ * https://en.wikipedia.org/wiki/Lexicographic_order */ -const subsequence = (str, seq, low) => { +export const subsequence = (str, seq, low, output = []) => { if (low <= str.length && str.length !== 0) { - console.log(seq) + output.push(seq) } for (let i = low; i < str.length; i++) { - subsequence(str, seq + str[i], i + 1) + subsequence(str, seq + str[i], i + 1, output) } + return output } - -const str = 'abcd' -subsequence(str, '', 0) diff --git a/Recursive/TowerOfHanoi.js b/Recursive/TowerOfHanoi.js index 0dc3ec6072..e43c426d33 100644 --- a/Recursive/TowerOfHanoi.js +++ b/Recursive/TowerOfHanoi.js @@ -1,16 +1,18 @@ // wiki - https://en.wikipedia.org/wiki/Tower_of_Hanoi // Recursive Javascript function to solve tower of hanoi -function TowerOfHanoi (n, fromRod, toRod, auxRod) { +export function TowerOfHanoi (n, from, to, aux, output = []) { if (n === 1) { - console.log(`Move disk 1 from rod ${fromRod} to rod ${toRod}`) - return + output.push(`Move disk 1 from rod ${from} to rod ${to}`) + return output } - TowerOfHanoi(n - 1, fromRod, auxRod, toRod) - console.log(`Move disk ${n} from rod ${fromRod} to rod ${toRod}`) - TowerOfHanoi(n - 1, auxRod, toRod, fromRod) + TowerOfHanoi(n - 1, from, aux, to, output) + output.push(`Move disk ${n} from rod ${from} to rod ${to}`) + TowerOfHanoi(n - 1, aux, to, from, output) + return output } -// Driver code -const n = 4 -TowerOfHanoi(n, 'A', 'C', 'B') -// A, C, B are the name of rods + +// Driver code (A, C, B are the name of rods) + +// const n = 4 +// TowerOfHanoi(n, 'A', 'C', 'B') diff --git a/Recursive/factorial.js b/Recursive/factorial.js index 0b1260c30d..ada7627c0d 100644 --- a/Recursive/factorial.js +++ b/Recursive/factorial.js @@ -3,14 +3,9 @@ // 5! = 1*2*3*4*5 = 120 // 2! = 1*2 = 2 -const factorial = (n) => { +export const factorial = (n) => { if (n === 0) { return 1 } return n * factorial(n - 1) } - -// testing -console.log(factorial(4)) -console.log(factorial(15)) -console.log(factorial(0)) diff --git a/Search/BinarySearch.js b/Search/BinarySearch.js index 4d4789d658..c822cfac60 100644 --- a/Search/BinarySearch.js +++ b/Search/BinarySearch.js @@ -49,42 +49,43 @@ function binarySearchIterative (arr, x, low = 0, high = arr.length - 1) { return -1 } -/* ---------------------------------- Test ---------------------------------- */ +export { binarySearchIterative, binarySearchRecursive } -const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -const stringArr = [ - 'Alpha', - 'Bravo', - 'Charlie', - 'Delta', - 'Echo', - 'Foxtrot', - 'Golf', - 'Hotel', - 'India', - 'Juliet', - 'Kilo', - 'Lima', - 'Mike', - 'November', - 'Oscar', - 'Papa', - 'Quebec', - 'Romeo', - 'Sierra', - 'Tango', - 'Uniform', - 'Victor', - 'Whiskey', - 'X-Ray', - 'Yankee', - 'Zulu' -] +/* ---------------------------------- Test ---------------------------------- */ -console.log(binarySearchRecursive(arr, 3)) -console.log(binarySearchIterative(arr, 7)) -console.log(binarySearchRecursive(arr, 13)) +// const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +// const stringArr = [ +// 'Alpha', +// 'Bravo', +// 'Charlie', +// 'Delta', +// 'Echo', +// 'Foxtrot', +// 'Golf', +// 'Hotel', +// 'India', +// 'Juliet', +// 'Kilo', +// 'Lima', +// 'Mike', +// 'November', +// 'Oscar', +// 'Papa', +// 'Quebec', +// 'Romeo', +// 'Sierra', +// 'Tango', +// 'Uniform', +// 'Victor', +// 'Whiskey', +// 'X-Ray', +// 'Yankee', +// 'Zulu' +// ] -console.log(binarySearchIterative(stringArr, 'Charlie')) -console.log(binarySearchRecursive(stringArr, 'Zulu')) -console.log(binarySearchIterative(stringArr, 'Sierra')) +// binarySearchRecursive(arr, 3) +// binarySearchIterative(arr, 7) +// binarySearchRecursive(arr, 13) +// binarySearchIterative(stringArr, 'Charlie') +// binarySearchRecursive(stringArr, 'Zulu') +// binarySearchIterative(stringArr, 'Sierra') diff --git a/Search/ExponentialSearch.js b/Search/ExponentialSearch.js index e46a5ee89e..7b023a606e 100644 --- a/Search/ExponentialSearch.js +++ b/Search/ExponentialSearch.js @@ -9,12 +9,12 @@ * */ -function binarySearch (arr, x, floor, ceiling) { +function binarySearch (arr, value, floor, ceiling) { // Middle index const mid = Math.floor((floor + ceiling) / 2) // If value is at the mid position return this position - if (arr[mid] === x) { + if (arr[mid] === value) { return mid } @@ -47,12 +47,8 @@ function exponentialSearch (arr, length, value) { return binarySearch(arr, value, i / 2, Math.min(i, length)) } -const arr = [2, 3, 4, 10, 40, 65, 78, 100] -const value = 78 -const result = exponentialSearch(arr, arr.length, value) +export { binarySearch, exponentialSearch } -if (result < 0) { - console.log('Element not found') -} else { - console.log('Element found at position :' + result) -} +// const arr = [2, 3, 4, 10, 40, 65, 78, 100] +// const value = 78 +// const result = exponentialSearch(arr, arr.length, value) diff --git a/Search/FibonacciSearch.js b/Search/FibonacciSearch.js index fcc8c85619..e1c3060d88 100644 --- a/Search/FibonacciSearch.js +++ b/Search/FibonacciSearch.js @@ -19,7 +19,7 @@ * the item (number) to be searched for and the length of the items in the array ****************************************************************************/ -const fibonacciSearch = (arr, x, n) => { +export const fibonacciSearch = (arr, x, n) => { let fib2 = 0 // (K-2)'th Fibonacci Number let fib1 = 1 // (K-1)'th Fibonacci Number. let fibK = fib2 + fib1 // Kth Fibonacci @@ -69,9 +69,9 @@ const fibonacciSearch = (arr, x, n) => { // element not found. return -1 return -1 } + // Example -const myArray = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100] -const n = myArray.length -const x = 90 -const fibFinder = fibonacciSearch(myArray, x, n) -console.log('Element found at index:', fibFinder) +// const myArray = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100] +// const n = myArray.length +// const x = 90 +// const fibFinder = fibonacciSearch(myArray, x, n) diff --git a/Search/InterpolationSearch.js b/Search/InterpolationSearch.js index c256fd8c7e..6ca3eea963 100644 --- a/Search/InterpolationSearch.js +++ b/Search/InterpolationSearch.js @@ -9,7 +9,7 @@ * */ -function interpolationSearch (arr, key) { +export function interpolationSearch (arr, key) { const length = arr.length - 1 let low = 0 let high = length @@ -38,9 +38,9 @@ function interpolationSearch (arr, key) { return -1 } -const arr = [2, 6, 8, 10, 12, 14, 16, 18, 20, 22, 26, 34, 39] +// const arr = [2, 6, 8, 10, 12, 14, 16, 18, 20, 22, 26, 34, 39] -console.log('Found at position :' + interpolationSearch(arr, 2)) -console.log('Found at position :' + interpolationSearch(arr, 12)) -console.log('Found at position :' + interpolationSearch(arr, 1000)) -console.log('Found at position :' + interpolationSearch(arr, 39)) +// interpolationSearch(arr, 2) +// interpolationSearch(arr, 12) +// interpolationSearch(arr, 1000) +// interpolationSearch(arr, 39) diff --git a/Search/LinearSearch.js b/Search/LinearSearch.js index 6b4211d40c..64a0e269bf 100644 --- a/Search/LinearSearch.js +++ b/Search/LinearSearch.js @@ -4,12 +4,12 @@ * for the target value until a match is found or until all the elements * have been searched. */ -function SearchArray (searchNum, ar) { +function SearchArray (searchNum, ar, output = v => console.log(v)) { const position = Search(ar, searchNum) if (position !== -1) { - console.log('The element was found at ' + (position + 1)) + output('The element was found at ' + (position + 1)) } else { - console.log('The element not found') + output('The element not found') } } @@ -21,7 +21,9 @@ function Search (theArray, key) { return -1 } -const ar = [1, 2, 3, 4, 5, 6, 7, 8, 9] -SearchArray(3, ar) -SearchArray(4, ar) -SearchArray(11, ar) +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 7a8c57bd3d..8ae5305015 100644 --- a/Search/QuickSelectSearch.js +++ b/Search/QuickSelectSearch.js @@ -11,7 +11,7 @@ * * [Reference](http://en.wikipedia.org/wiki/Quickselect) */ -function quickSelectSearch (array, k) { +export function quickSelectSearch (array, k) { if (!array || array.length <= k) { throw new Error('Invalid arguments') } @@ -49,7 +49,7 @@ function quickSelectSearch (array, k) { /* ---------------------------------- Test ---------------------------------- */ -const arr = [1121111, 21, 333, 41, 5, 66, 7777, 28, 19, 11110] -console.log(quickSelectSearch(arr, 5)) // [ 19, 21, 28, 41, 5, 66, 333, 11110, 1121111, 7777 ] -console.log(quickSelectSearch(arr, 2)) // [ 19, 5, 21, 41, 28, 333, 11110, 1121111, 7777, 66 ] -console.log(quickSelectSearch(arr, 7)) // [ 19, 5, 21, 41, 28, 66, 333, 7777, 11110, 1121111 ] +// const arr = [1121111, 21, 333, 41, 5, 66, 7777, 28, 19, 11110] +// quickSelectSearch(arr, 5) // [ 19, 21, 28, 41, 5, 66, 333, 11110, 1121111, 7777 ] +// quickSelectSearch(arr, 2) // [ 19, 5, 21, 41, 28, 333, 11110, 1121111, 7777, 66 ] +// quickSelectSearch(arr, 7) // [ 19, 5, 21, 41, 28, 66, 333, 7777, 11110, 1121111 ] diff --git a/Search/StringSearch.js b/Search/StringSearch.js index 614575107c..634f3979bb 100644 --- a/Search/StringSearch.js +++ b/Search/StringSearch.js @@ -35,7 +35,7 @@ function makeTable (str) { } // Find all the words that matches in a given string `str` -function stringSearch (str, word) { +export function stringSearch (str, word) { // find the prefix table in O(n) const prefixes = makeTable(word) const matches = [] @@ -80,4 +80,4 @@ function stringSearch (str, word) { return matches } -console.log(stringSearch('Hello search the position of me', 'pos')) +// stringSearch('Hello search the position of me', 'pos') diff --git a/Sorts/CountingSort.js b/Sorts/CountingSort.js index a31ea4455a..c7d495d92f 100644 --- a/Sorts/CountingSort.js +++ b/Sorts/CountingSort.js @@ -8,7 +8,7 @@ * Animated Visual: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html */ -const countingSort = (arr, min, max) => { +export const countingSort = (arr, min, max) => { // Create an auxiliary resultant array const res = [] // Create and initialize the frequency[count] array @@ -33,11 +33,5 @@ const countingSort = (arr, min, max) => { /** * Implementation of Counting Sort */ -const array = [3, 0, 2, 5, 4, 1] -// Before Sort -console.log('\n- Before Sort | Implementation of Counting Sort -') -console.log(array) -// After Sort -console.log('- After Sort | Implementation of Counting Sort -') -console.log(countingSort(array, 0, 5)) -console.log('\n') +// const array = [3, 0, 2, 5, 4, 1] +// countingSort(array, 0, 5) diff --git a/Sorts/FlashSort.js b/Sorts/FlashSort.js index 3bd1381f4d..292fc2cc79 100644 --- a/Sorts/FlashSort.js +++ b/Sorts/FlashSort.js @@ -6,7 +6,7 @@ * Wikipedia: https://en.wikipedia.org/wiki/Flashsort */ -function flashSort (arr) { +export function flashSort (arr) { let max = 0; let min = arr[0] const n = arr.length const m = ~~(0.45 * n) @@ -80,11 +80,5 @@ function flashSort (arr) { /** * Implementation of Flash Sort */ -const array = [3, 0, 2, 5, -1, 4, 1, -2] -// Before Sort -console.log('\n- Before Sort | Implementation of Flash Sort -') -console.log(array) -// After Sort -console.log('- After Sort | Implementation of Flash Sort -') -console.log(flashSort(array)) -console.log('\n') +// const array = [3, 0, 2, 5, -1, 4, 1, -2] +// flashSort(array) diff --git a/Sorts/GnomeSort.js b/Sorts/GnomeSort.js index 64434d5f8d..59f68b33ca 100644 --- a/Sorts/GnomeSort.js +++ b/Sorts/GnomeSort.js @@ -3,7 +3,7 @@ * more information: https://en.wikipedia.org/wiki/Gnome_sort * */ -function gnomeSort (items) { +export function gnomeSort (items) { if (items.length <= 1) { return } @@ -23,9 +23,5 @@ function gnomeSort (items) { // Implementation of gnomeSort -const ar = [5, 6, 7, 8, 1, 2, 12, 14] -// Array before Sort -console.log(ar) -gnomeSort(ar) -// Array after sort -console.log(ar) +// const ar = [5, 6, 7, 8, 1, 2, 12, 14] +// gnomeSort(ar) diff --git a/Sorts/HeapSort.js b/Sorts/HeapSort.js index 1f41c8ab03..a5d78c34d2 100644 --- a/Sorts/HeapSort.js +++ b/Sorts/HeapSort.js @@ -33,7 +33,7 @@ Array.prototype.heapify = function (index, heapSize) { * utilizing the heap property. * For more information see: https://en.wikipedia.org/wiki/Heapsort */ -function heapSort (items) { +export function heapSort (items) { const length = items.length for (let i = Math.floor(length / 2) - 1; i > -1; i--) { @@ -50,9 +50,5 @@ function heapSort (items) { // Implementation of heapSort -const ar = [5, 6, 7, 8, 1, 2, 12, 14] -// Array before Sort -console.log(ar) -heapSort(ar) -// Array after sort -console.log(ar) +// const ar = [5, 6, 7, 8, 1, 2, 12, 14] +// heapSort(ar) diff --git a/Sorts/HeapSortV2.js b/Sorts/HeapSortV2.js index 6f010eea47..8f0d91ace8 100644 --- a/Sorts/HeapSortV2.js +++ b/Sorts/HeapSortV2.js @@ -25,7 +25,7 @@ function swap (input, indexA, indexB) { [input[indexA], input[indexB]] = [input[indexB], input[indexA]] } -function heapSort (input) { +export function heapSort (input) { arrayLength = input.length for (let i = Math.floor(arrayLength / 2); i >= 0; i -= 1) { @@ -39,7 +39,3 @@ function heapSort (input) { heapRoot(input, 0) } } - -const arr = [3, 0, 2, 5, -1, 4, 1] -heapSort(arr) -console.log(arr) diff --git a/Sorts/InsertionSort.js b/Sorts/InsertionSort.js index 5812acf819..a6f44dd93d 100644 --- a/Sorts/InsertionSort.js +++ b/Sorts/InsertionSort.js @@ -4,7 +4,7 @@ * element one by one from unsorted part; insert into the sorted part at * the correct position and expand sorted part one element at a time. */ -function insertionSort (unsortedList) { +export function insertionSort (unsortedList) { const len = unsortedList.length for (let i = 1; i < len; i++) { let j @@ -19,7 +19,3 @@ function insertionSort (unsortedList) { unsortedList[j + 1] = tmp } } - -const arr = [5, 3, 1, 2, 4, 8, 3, 8] -insertionSort(arr) -console.log(arr) diff --git a/Sorts/IntroSort.js b/Sorts/IntroSort.js index 01d3c449d7..a99c4db924 100644 --- a/Sorts/IntroSort.js +++ b/Sorts/IntroSort.js @@ -244,10 +244,10 @@ function introsort (array, compare) { /** * @example Demo run of the sort routine * The data is randomly generated - * Prints RIGHT:) if the sort routine worked as expected - * If not prints WRONG!! + * Returns 'RIGHT:)' if the sort routine worked as expected, + * 'WRONG!!' otherwise */ -(function demo () { +function demo1 () { const data = [] const size = 1000000 let i = 0 @@ -268,18 +268,18 @@ function introsort (array, compare) { } } if (faulty) { - console.log('WRONG!!') + return 'WRONG!!' } else { - console.log('RIGHT:)') + return 'RIGHT:)' } -})(); +} /** * @example Demo run of the sort routine * using the default compare function and * comparing the results with Array.sort */ -(function demo () { +function demo2 () { const data = [] const data2 = [] const size = 1000000 @@ -300,8 +300,10 @@ function introsort (array, compare) { } } if (faulty) { - console.log('WRONG Implented Comparator!!') + return 'WRONG Implented Comparator!!' } else { - console.log('Comparator Works Fine:)') + return 'Comparator Works Fine:)' } -})() +} + +export { introsort, demo1, demo2 } diff --git a/Sorts/OddEvenSort.js b/Sorts/OddEvenSort.js index ade4c73604..ee4950f4ae 100644 --- a/Sorts/OddEvenSort.js +++ b/Sorts/OddEvenSort.js @@ -13,7 +13,7 @@ function swap (arr, i, j) { arr[j] = tmp } -function oddEvenSort (arr) { +export function oddEvenSort (arr) { let sorted = false while (!sorted) { sorted = true @@ -31,10 +31,3 @@ function oddEvenSort (arr) { } } } -const testArray = [5, 6, 7, 8, 1, 2, 12, 14, 5, 3, 2, 2] - -// Array before sort -console.log(testArray) -oddEvenSort(testArray) -// Array after sort -console.log(testArray) diff --git a/Sorts/PigeonHoleSort.js b/Sorts/PigeonHoleSort.js index fc22650491..333027c68c 100644 --- a/Sorts/PigeonHoleSort.js +++ b/Sorts/PigeonHoleSort.js @@ -6,7 +6,7 @@ https://en.wikipedia.org/wiki/Pigeonhole_sort * (n) and the length of the range of possible key values (N) * are approximately the same. */ -function pigeonHoleSort (arr) { +export function pigeonHoleSort (arr) { let min = arr[0] let max = arr[0] @@ -14,8 +14,6 @@ function pigeonHoleSort (arr) { if (arr[i] > max) { max = arr[i] } if (arr[i] < min) { min = arr[i] } } - console.log(max) - console.log(min) const range = max - min + 1 const pigeonhole = Array(range).fill(0) @@ -32,7 +30,3 @@ function pigeonHoleSort (arr) { } } } -// Driver code -const arr = [8, 3, 2, 7, 4, 6, 8] -pigeonHoleSort(arr) -console.log(arr) diff --git a/Sorts/RadixSort.js b/Sorts/RadixSort.js index 3696aba961..a49f3c9228 100644 --- a/Sorts/RadixSort.js +++ b/Sorts/RadixSort.js @@ -4,7 +4,7 @@ * significant position. * For more information see: https://en.wikipedia.org/wiki/Radix_sort */ -function radixSort (items, RADIX) { +export function radixSort (items, RADIX) { // default radix is then because we usually count to base 10 if (RADIX === undefined || RADIX < 1) { RADIX = 10 @@ -41,12 +41,3 @@ function radixSort (items, RADIX) { } return items } - -// Implementation of radixSort - -const ar = [5, 6, 7, 8, 1, 2, 12, 14] -// Array before Sort -console.log(ar) -radixSort(ar) -// Array after sort -console.log(ar) diff --git a/Sorts/SelectionSort.js b/Sorts/SelectionSort.js index c4a11e354e..cbb038fc3e 100644 --- a/Sorts/SelectionSort.js +++ b/Sorts/SelectionSort.js @@ -8,7 +8,7 @@ *from the unsorted subarray is picked and moved to the sorted subarray. */ -const selectionSort = (list) => { +export const selectionSort = (list) => { if (!Array.isArray(list)) { throw new TypeError('Given input is not an array') } @@ -33,18 +33,3 @@ const selectionSort = (list) => { } return items } - -/* Implementation of Selection Sort - -(() => { - let array = [5, 6, 7, 8, 1, 2, 12, 14] - // Array before Sort - console.log(array) - array = selectionSort(array) - // Array after sort - console.log(array) -})() - -*/ - -export { selectionSort } diff --git a/Sorts/ShellSort.js b/Sorts/ShellSort.js index e32af561c5..b2286bb108 100644 --- a/Sorts/ShellSort.js +++ b/Sorts/ShellSort.js @@ -3,7 +3,7 @@ * more information: https://en.wikipedia.org/wiki/Shellsort * */ -function shellSort (items) { +export function shellSort (items) { let interval = 1 while (interval < items.length / 3) { @@ -25,12 +25,3 @@ function shellSort (items) { } return items } - -// Implementation of shellSort - -const ar = [5, 6, 7, 8, 1, 2, 12, 14] -// Array before Sort -console.log(ar) -shellSort(ar) -// Array after sort -console.log(ar) diff --git a/Sorts/TimSort.js b/Sorts/TimSort.js index 07556404be..aaeef415fe 100644 --- a/Sorts/TimSort.js +++ b/Sorts/TimSort.js @@ -85,10 +85,10 @@ const Merge = (array, left, mid, right) => { /** * @example Test of Timsort functions. * Data is randomly generated. - * Prints "RIGHT" if it works as expected, + * Return "RIGHT" if it works as expected, * otherwise "FAULTY" */ -(() => { +const demo = () => { const size = 1000000 const data = Array(size) for (let i = 0; i < size; i++) { @@ -103,8 +103,10 @@ const Merge = (array, left, mid, right) => { } Timsort(data) if (isSorted(data)) { - console.log('RIGHT') + return 'RIGHT' } else { - console.log('FAULTY') + return 'FAULTY' } -})() +} + +export { Timsort, demo } diff --git a/Sorts/TopologicalSort.js b/Sorts/TopologicalSort.js index c9c5dc5e0d..7bbc032c44 100644 --- a/Sorts/TopologicalSort.js +++ b/Sorts/TopologicalSort.js @@ -1,5 +1,5 @@ -function TopologicalSorter () { +export function TopologicalSorter () { const graph = {} let isVisitedNode let finishTimeCount @@ -49,11 +49,11 @@ function TopologicalSorter () { } /* TEST */ -const topoSorter = new TopologicalSorter() -topoSorter.addOrder(5, 2) -topoSorter.addOrder(5, 0) -topoSorter.addOrder(4, 0) -topoSorter.addOrder(4, 1) -topoSorter.addOrder(2, 3) -topoSorter.addOrder(3, 1) -console.log(topoSorter.sortAndGetOrderedItems()) +// const topoSorter = new TopologicalSorter() +// topoSorter.addOrder(5, 2) +// topoSorter.addOrder(5, 0) +// topoSorter.addOrder(4, 0) +// topoSorter.addOrder(4, 1) +// topoSorter.addOrder(2, 3) +// topoSorter.addOrder(3, 1) +// topoSorter.sortAndGetOrderedItems() diff --git a/Sorts/WiggleSort.js b/Sorts/WiggleSort.js index 4c303c672a..aa19d596e6 100644 --- a/Sorts/WiggleSort.js +++ b/Sorts/WiggleSort.js @@ -4,24 +4,18 @@ * */ -/* eslint no-extend-native: ["off", { "exceptions": ["Object"] }] */ -Array.prototype.wiggleSort = function () { - for (let i = 0; i < this.length; ++i) { +export const wiggleSort = function (arr) { + for (let i = 0; i < arr.length; ++i) { const shouldNotBeLessThan = i % 2 - const isLessThan = this[i] < this[i + 1] + const isLessThan = arr[i] < arr[i + 1] if (shouldNotBeLessThan && isLessThan) { - [this[i], this[i + 1]] = [this[i + 1], this[i]] + [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]] } } - return this + return arr } // Implementation of wiggle sort -const arr = [3, 5, 2, 1, 6, 4] -// Array before Wiggle Sort -console.log(arr) // [3, 5, 2, 1, 6, 4] - -arr.wiggleSort() -// Array after wiggle sort -console.log(arr) // [ 3, 5, 2, 6, 1, 4 ] +// > wiggleSort([3, 5, 2, 1, 6, 4]) +// [ 3, 5, 2, 6, 1, 4 ] diff --git a/String/AlternativeStringArrange.js b/String/AlternativeStringArrange.js index 9b722a1f9e..b07b0a70d7 100644 --- a/String/AlternativeStringArrange.js +++ b/String/AlternativeStringArrange.js @@ -41,4 +41,4 @@ const AlternativeStringArrange = (str1, str2) => { return outStr } -module.exports = AlternativeStringArrange +export { AlternativeStringArrange } diff --git a/String/CheckKebabCase.js b/String/CheckKebabCase.js index 30bbe976e3..6e79ba6a5e 100644 --- a/String/CheckKebabCase.js +++ b/String/CheckKebabCase.js @@ -17,4 +17,4 @@ const CheckKebabCase = (varName) => { return pat.test(varName) && !varName.includes('_') } -module.exports = CheckKebabCase +export { CheckKebabCase } diff --git a/String/CheckPascalCase.js b/String/CheckPascalCase.js index 6babce5f0c..2e4c1ff3fa 100644 --- a/String/CheckPascalCase.js +++ b/String/CheckPascalCase.js @@ -17,4 +17,4 @@ const CheckPascalCase = (VarName) => { return pat.test(VarName) } -module.exports = CheckPascalCase +export { CheckPascalCase } diff --git a/String/CheckRearrangePalindrome.js b/String/CheckRearrangePalindrome.js index e4a8b6ca6a..2f0e698ef2 100644 --- a/String/CheckRearrangePalindrome.js +++ b/String/CheckRearrangePalindrome.js @@ -6,7 +6,7 @@ * **/ -const palindromeRearranging = (str) => { +export const palindromeRearranging = (str) => { // check that input is a string if (typeof str !== 'string') { return 'Not a string' @@ -27,5 +27,9 @@ const palindromeRearranging = (str) => { } // testing -console.log(palindromeRearranging('aaeccrr')) // true -console.log(palindromeRearranging('leve')) // false + +// > palindromeRearranging('aaeccrr') +// true + +// > palindromeRearranging('leve') +// false diff --git a/String/DiceCoefficient.js b/String/DiceCoefficient.js index b2f3a34be9..ca9471159b 100644 --- a/String/DiceCoefficient.js +++ b/String/DiceCoefficient.js @@ -44,8 +44,7 @@ function diceCoefficient (stringA, stringB) { // cut 0.xxxxxx to 0.xx for simplicity dice = Math.floor(dice * 100) / 100 - console.log('Dice coefficient of', stringA, 'and', stringB, 'is', dice) - return dice } + export { diceCoefficient } diff --git a/String/GenerateGUID.js b/String/GenerateGUID.js index 8688199975..f30207382b 100644 --- a/String/GenerateGUID.js +++ b/String/GenerateGUID.js @@ -4,7 +4,7 @@ The script uses `Math.random` in combination with the timestamp for better rando The function generate an RFC4122 (https://www.ietf.org/rfc/rfc4122.txt) version 4 UUID/GUID */ -const Guid = () => { +export const Guid = () => { const pattern = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' let currentDateMilliseconds = new Date().getTime() return pattern.replace(/[xy]/g, currentChar => { @@ -14,4 +14,5 @@ const Guid = () => { }) } -console.log(Guid()) // 'edc848db-3478-1760-8b55-7986003d895f' +// > Guid() +// 'edc848db-3478-1760-8b55-7986003d895f' diff --git a/String/LevenshteinDistance.js b/String/LevenshteinDistance.js index 428e712653..1b6ece70c7 100644 --- a/String/LevenshteinDistance.js +++ b/String/LevenshteinDistance.js @@ -37,14 +37,6 @@ const levenshteinDistance = (a, b) => { } } - console.log( - 'Levenshtein Distance between ' + - a + - ' and ' + - b + - ' is = ' + - distanceMatrix[b.length][a.length] - ) return distanceMatrix[b.length][a.length] } diff --git a/Timing-Functions/IntervalTimer.js b/Timing-Functions/IntervalTimer.js index 2864a32c27..2eeed116e9 100644 --- a/Timing-Functions/IntervalTimer.js +++ b/Timing-Functions/IntervalTimer.js @@ -63,7 +63,7 @@ class IntervalTimer { * Saturday, 01 August 2020 8:33 AM * @description Example usage */ -const ExampleIntervalTimer = function () { +const ExampleIntervalTimer = function (output = v => console.log(v)) { /** * Create am object with default settings. * @type {IntervalTimer} Used to get timing information. @@ -82,12 +82,12 @@ const ExampleIntervalTimer = function () { // ... A test ... // The time taken to run the test. - console.log(timer.getElapsedTime(initOffset)) + output(timer.getElapsedTime(initOffset)) /** * Returns the elapsed time and resets the timer to 0. */ - console.log(timer.resetTimer()) + output(timer.resetTimer()) } -ExampleIntervalTimer() +export { IntervalTimer, ExampleIntervalTimer } diff --git a/Trees/BreadthFirstTreeTraversal.js b/Trees/BreadthFirstTreeTraversal.js index b9195144de..e50c97aa6c 100644 --- a/Trees/BreadthFirstTreeTraversal.js +++ b/Trees/BreadthFirstTreeTraversal.js @@ -22,7 +22,7 @@ class BinaryTree { for (let i = 1; i <= h; i++) { this.traverseLevel(this.root, i) } - return this.traversal.toLocaleString() + return this.traversal } // Computing the height of the tree @@ -48,19 +48,4 @@ class BinaryTree { } } -const binaryTree = new BinaryTree() -const root = new Node(7) -root.left = new Node(5) -root.right = new Node(8) -root.left.left = new Node(3) -root.left.right = new Node(6) -root.right.right = new Node(9) -binaryTree.root = root - -console.log(binaryTree.breadthFirst()) - -// 7 -// / \ -// 5 8 -// / \ \ -// 3 6 9 +export { BinaryTree, Node } diff --git a/Trees/test/BreadthFirstTreeTraversal.test.js b/Trees/test/BreadthFirstTreeTraversal.test.js new file mode 100644 index 0000000000..8b4cae7ead --- /dev/null +++ b/Trees/test/BreadthFirstTreeTraversal.test.js @@ -0,0 +1,27 @@ +import { BinaryTree, Node } from '../BreadthFirstTreeTraversal' + +describe('Breadth First Tree Traversal', () => { + const binaryTree = new BinaryTree() + + const root = new Node(7) + root.left = new Node(5) + root.right = new Node(8) + root.left.left = new Node(3) + root.left.right = new Node(6) + root.right.right = new Node(9) + binaryTree.root = root + + // Vizualization : + // + // 7 + // / \ + // 5 8 + // / \ \ + // 3 6 9 + + it('Binary tree - Level order traversal', () => { + expect(binaryTree.traversal).toStrictEqual([]) + const traversal = binaryTree.breadthFirst() + expect(traversal).toStrictEqual([7, 5, 8, 3, 6, 9]) + }) +}) diff --git a/babel.config.js b/babel.config.cjs similarity index 100% rename from babel.config.js rename to babel.config.cjs diff --git a/package.json b/package.json index a870694dd0..d4f8414ead 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "javascript", "version": "1.0.0", + "type": "module", "description": "A repository for All algorithms implemented in Javascript (for educational purposes only)", "main": "", "scripts": {