Repository: scotch-io/ultimate-guide-to-javascript-algorithms Branch: master Commit: 58a4c4ffb1be Files: 52 Total size: 24.6 KB Directory structure: gitextract_iez748fz/ ├── .gitignore ├── Beginner/ │ ├── README.md │ ├── capSentence/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── chunkArray/ │ │ ├── index-FINISHED.js │ │ ├── index-START.js │ │ └── test.js │ ├── factorial/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── falsyBouncer/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── fibonacci/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── fizzBuzz/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── hammingDistance/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── isAnagram/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── longestWord/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── maxRecurringChar/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── mergeArrays/ │ │ ├── index-FINISHED.js │ │ ├── index-START.js │ │ └── test.js │ ├── palindromeChecker/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── reverseString/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── searchReplace/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ ├── vowelsCounter/ │ │ ├── index-SOLUTION.js │ │ ├── index-START.js │ │ └── test.js │ └── whereIBelong/ │ ├── index-SOLUTION.js │ ├── index-START.js │ └── test.js ├── README.md └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules ================================================ FILE: Beginner/README.md ================================================ # This contains all beginner algorithms and data structures ================================================ FILE: Beginner/capSentence/index-SOLUTION.js ================================================ // USING A FOREACH LOOP function capSentence(text) { let wordsArray = text.toLowerCase().split(' ') let capsArray = [] wordsArray.forEach(word => { capsArray.push(word[0].toUpperCase() + word.slice(1)) }); return capsArray.join(' ') } // USING .MAP() AND .SLICE() function capSentence(text) { let wordsArray = text.toLowerCase().split(' ') let capsArray = wordsArray.map(word=>{ return word[0].toUpperCase() + word.slice(1) }) return capsArray.join(' ') } // USING .MAP() AND .REPLACE() function capSentence(text) { let wordsArray = text.toLowerCase().split(' ') let capsArray = wordsArray.map( word=>{ return word.replace(word[0], word[0].toUpperCase()) }) return capsArray.join(' ') } ================================================ FILE: Beginner/capSentence/index-START.js ================================================ /* CHALLENGE Given a sentence containing two or more words, return the equivalent of the sentence when capitalised. E.g capSentence('the tales of scotch!') // would return 'The Tales Of Scotch!' */ function capSentence(text) { // Code goes here } module.exports = capSentence ================================================ FILE: Beginner/capSentence/test.js ================================================ const capSentence = require('./index-START') test('capSentence is a function', () => { expect(typeof capSentence).toEqual('function') }) test('capitalizes the first letter of each word in a lowercase sentence', () => { expect(capSentence('i must confess, this is so much fun.')).toEqual( 'I Must Confess, This Is So Much Fun.' ) }) test('capitalizes the first letter of each word in an uppercase sentence', () => { expect(capSentence('THIS ONE IS FOR SCOTCH.')).toEqual( 'This One Is For Scotch.' ) }) test('capitalizes the first letter of each word in mixed cased sentences', () => { expect(capSentence('i woulD lOVe to spEAk at jsconF.')).toEqual( 'I Would Love To Speak At Jsconf.' ) }) ================================================ FILE: Beginner/chunkArray/index-FINISHED.js ================================================ // LOOPING THROUGH THE ARRAY function chunkArray(array, size) { let result = [] for (value of array){ let lastArray = result[result.length -1 ] if(!lastArray || lastArray.length == size){ result.push([value]) }else{ lastArray.push(value) } } return result } // LOOPING THROUGH THE NUMBER OF CHUNKS function chunkArray(array, size) { let result = [] let arrayCopy = [...array] while (arrayCopy.length > 0) { result.push(arrayCopy.splice(0, size)) } return result } // USING .SLICE() function chunkArray(array, size) { let result = [] for (i = 0; i < array.length; i += size) { let chunk = array.slice(i, i + size) result.push(chunk) } return result } //RECURSION function chunkArray(array, size) { if(array.length <= size){ return [array] } return [array.slice(0,size), ...chunkArray(array.slice(size), size)] } ================================================ FILE: Beginner/chunkArray/index-START.js ================================================ /* Given two or more arrays, write a function that combines their elements into one array without any repetition. E.g mergeArrays([1,2,3,3,3], [1,4,5,2]) // should return [1,2,3,4,5] */ function chunkArray(array, size) { // Code goes here } module.exports = chunkArray ================================================ FILE: Beginner/chunkArray/test.js ================================================ const chunkArray = require('./index-START'); test('chunkArray is a function', () => { expect(typeof chunkArray).toEqual('function'); }); test('Chunks array of 10 elements in twos', () => { const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const chunkedArray = chunkArray(arr, 2); expect(chunkedArray).toEqual([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]); }); test('Chunks array of 13 elements in five and some', () => { const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; const chunkedArray = chunkArray(arr, 5); expect(chunkedArray).toEqual([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]]); }); ================================================ FILE: Beginner/factorial/index-SOLUTION.js ================================================ // USING A FOR LOOP function factorial(n) { if (n <= 1) { return 1 } for (let i = n - 1; i >= 1; i--) { n *= i; } return n; } // USING A WHILE LOOP function factorial(n) { var result = n if (n <= 1) { return 1 } while (n > 1) { n-- result *= n } return result } // USING RECURSION function factorial(n) { if (n === 0) { return 1 } return n * factorial(n - 1) } // USING MEMOIZATION function factorial(n, memo) { memo = memo || {} if(memo[n]){ return memo[n] } if (n === 0) { return 1 } return memo[n] = n * factorial(n - 1, memo) } ================================================ FILE: Beginner/factorial/index-START.js ================================================ /* Write a function that returns the factorial of the provided integer(n). E.g factorial(5) // should return 120 */ function factorial(n, memo) { memo = memo || {} if(memo[n]){ return memo[n] } if (n === 0) { return 1 } return memo[n] = n * factorial(n - 1, memo) } module.exports = factorial ================================================ FILE: Beginner/factorial/test.js ================================================ const factorial = require('./index-START') test('factorial is a function', () => { expect(typeof factorial).toEqual('function') }) test('returns the factorial of 20', () => { expect(factorial(10)).toEqual(3628800) }) test('returns the factorial of 20', () => { expect(factorial(20)).toEqual(2432902008176640000) }) ================================================ FILE: Beginner/falsyBouncer/index-SOLUTION.js ================================================ // USING A FOR OF LOOP function falsyBouncer(array) { let result =[] for (value of array){ if(value){ result.push(value) } } return result } // USING .FILTER() function falsyBouncer(array) { return array.filter((value) =>{ return Boolean(value) }) } ================================================ FILE: Beginner/falsyBouncer/index-START.js ================================================ /* Given an array, remove all falsy values from the array and return an array of only truthy values. E.g falsyBouncer([1, 0, null, '', 5]) // should return [1,5] */ function falsyBouncer(array) { // Code goes here } module.exports = falsyBouncer ================================================ FILE: Beginner/falsyBouncer/test.js ================================================ const falsyBouncer = require('./index-START'); test('falsyBouncer is a function', () => { expect(typeof falsyBouncer).toEqual('function'); }); test('Removes all falsy values', () => { expect(falsyBouncer([1, 0, null, '', 5])).toEqual([1, 5]); }) test('Removes all falsy values', () => { expect(falsyBouncer([NaN, 0, null, '', undefined])).toEqual([]); }) ================================================ FILE: Beginner/fibonacci/index-SOLUTION.js ================================================ // AN ITERATIVE APPROACH function fibonacci(n) { let previous = 1, current = 1 if (n <= 1) { return 1 } else { let counter = n - 1 while (counter) { let temp = current current += previous previous = temp counter -- } } return current } // A RECURSIVE SOLUTION function fibonacci(n) { if (n <= 1) { return 1 } return fibonacci(n - 1) + fibonacci(n - 2) } // USING MEMOIZATION function fibonacci(n,memo) { memo = memo || {} if (memo[n]) { return memo[n] } if (n <= 1) { return 1 } return memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo) } ================================================ FILE: Beginner/fibonacci/index-START.js ================================================ /* Write a function to return the nth element in Fibonacci sequence, where the sequence is: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …] */ function fibonacci(n) { // Code goes here } module.exports = fibonacci ================================================ FILE: Beginner/fibonacci/test.js ================================================ const fibonacci = require('./index-START') test('fibonacci is a function', () => { expect(typeof fibonacci).toEqual('function') }) test('returns the 6th fibonacci number', () => { expect(fibonacci(6)).toEqual(13) }) test('returns the 20th fibonacci number', () => { expect(fibonacci(20)).toEqual(10946) }) ================================================ FILE: Beginner/fizzBuzz/index-SOLUTION.js ================================================ // FOR LOOP SOLUTION function fizzBuzz(n) { for (let i = 1; i <= n; i++) { // Is a multiple of 3 and 5? if (i % 15 === 0) { console.log('fizzbuzz') } else if (i % 3 === 0) { // Is a multiple of 3? console.log('fizz') } else if (i % 5 === 0) { // Is a multiple of 5? console.log('buzz') } else { // Is neither of the above? console.log(i) } } } // CLEANER AND SMALLER function fizzBuzz(n) { for (let i = 0; i < n;) console.log((++i % 3 ? '' : 'fizz') + (i % 5 ? '' : 'buzz') || i) } ================================================ FILE: Beginner/fizzBuzz/index-START.js ================================================ /* Write a program that prints the numbers from 1 to n. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. */ function fizzBuzz(n) { // Code goes here } module.exports = fizzBuzz ================================================ FILE: Beginner/fizzBuzz/test.js ================================================ const fizzBuzz = require('./index-START'); test('fizzBuzz is a function', () => { expect(fizzBuzz).toBeDefined(); }); test('Calling fizzbuzz with `10` prints out 10 statements', () => { fizzBuzz(10); expect(console.log.mock.calls.length).toEqual(10); }); test('Calling fizzbuzz with 15 prints out the correct values', () => { fizzBuzz(15); expect(console.log.mock.calls[0][0]).toEqual(1); expect(console.log.mock.calls[1][0]).toEqual(2); expect(console.log.mock.calls[2][0]).toEqual('fizz'); expect(console.log.mock.calls[3][0]).toEqual(4); expect(console.log.mock.calls[4][0]).toEqual('buzz'); expect(console.log.mock.calls[5][0]).toEqual('fizz'); expect(console.log.mock.calls[6][0]).toEqual(7); expect(console.log.mock.calls[7][0]).toEqual(8); expect(console.log.mock.calls[8][0]).toEqual('fizz'); expect(console.log.mock.calls[9][0]).toEqual('buzz'); expect(console.log.mock.calls[10][0]).toEqual(11); expect(console.log.mock.calls[11][0]).toEqual('fizz'); expect(console.log.mock.calls[12][0]).toEqual(13); expect(console.log.mock.calls[13][0]).toEqual(14); expect(console.log.mock.calls[14][0]).toEqual('fizzbuzz'); }); beforeEach(() => { jest.spyOn(console, 'log').mockImplementation(() => {}); }); afterEach(() => { console.log.mockRestore(); }); ================================================ FILE: Beginner/hammingDistance/index-SOLUTION.js ================================================ // USING FOR LOOP function hammingDistance(stringA, stringB) { let result = 0 if (stringA.length == stringB.length) { for (let i = 0; i < stringA.length; i++) { if (stringA[i].toLowerCase() != stringB[i].toLowerCase()) { result++ } } return result } else { throw new Error('Strings do not have equal length') } } ================================================ FILE: Beginner/hammingDistance/index-START.js ================================================ /* CHALLENGE Given two strings of equal length, calculate and return the the hamming distance. E.g hammingDistance('rover', 'river') // should return 1 */ function hammingDistance(stringA, stringB) { // Code goes here } module.exports = hammingDistance ================================================ FILE: Beginner/hammingDistance/test.js ================================================ const hammingDistance = require('./index-START') test('hammingDistance is a function', () => { expect(typeof hammingDistance).toEqual('function') }) test('returns the hamming distance for letters', () => { expect(hammingDistance('river', 'rover')).toEqual(1) }) test('returns the hamming distance for numbers', () => { expect(hammingDistance('1011101', '1001001')).toEqual(2) }) test('returns the hamming distance for letters', () => { expect(hammingDistance('karolin', 'kerstin')).toEqual(3) }) test('returns the hamming distance for letters', () => { expect(hammingDistance('drummer', 'dresser')).toEqual(3) }) ================================================ FILE: Beginner/isAnagram/index-SOLUTION.js ================================================ // DIRECT COMPARISON function isAnagram(stringA, stringB) { const sanitizeString = function (str) { return str.toLowerCase().replace(/[^a-z\d]/g, '').split('').sort().join(''); } return sanitizeString(stringA) == sanitizeString(stringB) } // CHARACTER MAP COMPARISON function isAnagram(stringA, stringB) { function createCharMap(text) { let charMap = {} for (let char of text) { if (charMap.hasOwnProperty(char)) { charMap[char]++ } else { charMap[char] = 1 } } return charMap } if (stringA.length === stringB.length) { let stringAMap = createCharMap(stringA) let stringBMap = createCharMap(stringB) for (let char in stringAMap) { if (stringAMap[char] !== stringBMap[char]) { return false } } return true } else { return false } } ================================================ FILE: Beginner/isAnagram/index-START.js ================================================ /* CHALLENGE Given a two strings, write an algorithm to check if they are anagrams of each other. Return true if the pass the test and false if they don't. E.g isAnagram('silent', 'listen') // should return true */ function isAnagram(stringA, stringB) { // Code goes here } module.exports = isAnagram ================================================ FILE: Beginner/isAnagram/test.js ================================================ const isAnagram = require('./index-START') test('isAnagram is a function', () => { expect(typeof isAnagram).toEqual('function') }) test('"dog" is an anagram of "god"', () => { expect(isAnagram('dog', 'god')).toBeTruthy() }) test('"Scotchy is Scotch!" is an anagram of "Scotch is Scotchy!"', () => { expect(isAnagram('Scotchy is Scotch!', 'Scotch is Scotchy!')).toBeTruthy() }) test('"I do not work weekends." is not an anagram of "I do not work weekdays!"', () => { expect(isAnagram('I do not work weekends.', 'I do not work weekdays!')).toBeFalsy() }) ================================================ FILE: Beginner/longestWord/index-SOLUTION.js ================================================ // USING A FOR LOOP function longestWord(text) { let wordArray = text.split(' ') let maxLength = 0 let result = '' for (let i = 0; i < wordArray.length; i++) { if (wordArray[i].length > maxLength) { maxLength = wordArray[i].length result = wordArray[i] } } return result } // USING .REDUCE() function longestWord(text) { var result = text.split(' ').reduce((maxLengthWord, currentWord) => { if (currentWord.length > maxLengthWord.length) { return currentWord } else { return maxLengthWord } }, "") return result } // USING .SORT() function longestWord(text) { var sortedArray = text.split(' ') .sort((wordA, wordB) => wordB.length - wordA.length) return sortedArray[0] } ================================================ FILE: Beginner/longestWord/index-START.js ================================================ /* CHALLENGE Given a string of text, write an algorithm that returns the text received in a reversed format. E.g reverseString('algorithms') // should return 'smhtirogla' */ function longestWord(text) { // Code goes here } module.exports = longestWord ================================================ FILE: Beginner/longestWord/test.js ================================================ const longestWord = require('./index-START') test('longestWord is a function', () => { expect(typeof longestWord).toEqual('function'); }); test('returns the longet word in a mixed case string of text', () => { expect(longestWord('Top Shelf Web Development Training on Scotch') ).toEqual('Development'); }); test('returns the longet word in a lowercase string', () => { expect(longestWord('the ultimate guide to js algorithms') ).toEqual('algorithms'); }); test('returns the longet word in an uppercase string', () => { expect(longestWord('BUILDING FOR THE NEXT BILLION USERS') ).toEqual('BUILDING'); }); ================================================ FILE: Beginner/maxRecurringChar/index-SOLUTION.js ================================================ // FOR...IN ITERATION METHOD function maxRecurringChar(text) { let charMap = {} let maxCharValue = 0 let maxChar = '' for (let char of text) { if (charMap.hasOwnProperty(char)) { charMap[char]++ } else { charMap[char] = 1 } } for (let char in charMap) { if (charMap[char] > maxCharValue) { maxCharValue = charMap[char] maxChar = char } } return maxChar } // FORMING ARRAYS FROM THE CHARACTER MAP METHOD function maxRecurringChar(text) { let charMap = {} let charArray =[] let vaulesArray = [] let maxCharValue = 0 for (let char of text) { if (charMap.hasOwnProperty(char)) { charMap[char]++ } else { charMap[char] = 1 } } charArray = Object.keys(charMap) vaulesArray = Object.values(charMap) maxCharValue = Math.max(...vaulesArray) return charArray[vaulesArray.indexOf(maxCharValue)] } ================================================ FILE: Beginner/maxRecurringChar/index-START.js ================================================ /* CHALLENGE Given a string of text, find and return the most recurring character. e.g maxRecurringChar('aabacada') // will return 'a' */ function maxRecurringChar(text) { // Code goes here } module.exports = maxRecurringChar; ================================================ FILE: Beginner/maxRecurringChar/test.js ================================================ const maxRecurringChar = require('./index-START'); test('maxRecurringChar is a function', () => { expect(typeof maxRecurringChar).toEqual('function'); }); test('Finds the most frequently used character', () => { expect(maxRecurringChar('sisusbsnshsjsmskslstsw')).toEqual('s'); }); test('Finds the most frequently used character even with mixed capitalization', () => { expect(maxRecurringChar('AbAdAabnmkAAAynjfaA')).toEqual('A'); }); test('Finds the most used number as well', () => { expect(maxRecurringChar('b2n3n2m2l2k2i2o2')).toEqual('2'); }); ================================================ FILE: Beginner/mergeArrays/index-FINISHED.js ================================================ // USING A SET function mergeArrays(...arrays) { let jointArray = [] arrays.forEach(array => { jointArray = [...jointArray, ...array] }); return [...new Set([...jointArray])] } // USING ARRAY.FROM() WITH SET function mergeArrays(...arrays) { let jointArray = [] arrays.forEach(array => { jointArray = [...jointArray, ...array] }); return Array.from(new Set([...jointArray])) } // USING .FILTER() function mergeArrays(...arrays) { let jointArray = [] arrays.forEach(array => { jointArray = [...jointArray, ...array] }) const uniqueArray = jointArray.filter((item,index) => jointArray.indexOf(item) === index) return uniqueArray } // USING .REDUCE() function mergeArrays(...arrays) { let jointArray = [] arrays.forEach(array => { jointArray = [...jointArray, ...array] }) const uniqueArray = jointArray.reduce((newArray, item) =>{ if (newArray.includes(item)){ return newArray } else { return [...newArray, item] } }, []) return uniqueArray } ================================================ FILE: Beginner/mergeArrays/index-START.js ================================================ /* Given two or more arrays, write a function that combines their elements into one array without any repetition. E.g mergeArrays([1,2,3,3,3], [1,4,5,2]) // should return [1,2,3,4,5] */ function mergeArrays(...arrays) { let jointArray = [] arrays.forEach(array => { jointArray = [...jointArray, ...array] }); return [...new Set([...jointArray])] } module.exports = mergeArrays ================================================ FILE: Beginner/mergeArrays/test.js ================================================ const mergeArrays = require('./index-START'); test('mergeArrays is a function', () => { expect(typeof mergeArrays).toEqual('function'); }); test('Combines 5 arrays of numbers without dubplicates', () => { expect(mergeArrays([1,2],[2,3],[3,4],[4,5])).toEqual([1,2,3,4,5]); }); test('Combines 3 arrays of strings without dubplicates', () => { expect(mergeArrays(['a','b','z'],['m','n','a'],['z','y'])).toEqual(['a','b', 'z', 'm', 'n', 'y']); }); ================================================ FILE: Beginner/palindromeChecker/index-SOLUTION.js ================================================ // AN INTUITIVE APPROACH function palindromeChecker(text) { var reversedText = text.toLowerCase() .split('').reverse().join('') return text === reversedText } // LOOPING THROUGH AND COMPARING CHARACTERS function palindromeChecker(text) { let charArray = text.toLowerCase().split('') let result = charArray.every((letter, index) => { return letter === charArray[charArray.length - index - 1]; }) return result } // LOOPING THROUGH AND COMPARING CHARACTERS(OPTIMIZED) function palindromeChecker(text) { var textLen = text.length; for (var i = 0; i < textLen / 2; i++) { if (text[i] !== text[textLen - 1 - i]) { return false; } } return true; } ================================================ FILE: Beginner/palindromeChecker/index-START.js ================================================ /* CHALLENGE Given a string of text, return true or false indicating whether or not the text is a palindrome. e.g palindromeChecker('racecar') // will return true */ function palindromeChecker(text) { v// Code goes here } module.exports = palindromeChecker; ================================================ FILE: Beginner/palindromeChecker/test.js ================================================ const palindromeChecker = require('./index-START'); test('palindromeChecker is a function', () => { expect(typeof palindromeChecker).toEqual('function'); }); test('"php" is a palindrome', () => { expect(palindromeChecker('php')).toBeTruthy(); }); test('" php " is not a palindrome', () => { expect(palindromeChecker(' php ')).toBeFalsy(); }); test('"developer" is not a palindrome', () => { expect(palindromeChecker('developer')).toBeFalsy(); }); test('"2002" a palindrome', () => { expect(palindromeChecker('2002')).toBeTruthy(); }); ================================================ FILE: Beginner/reverseString/index-SOLUTION.js ================================================ // CHAINING BUILT-IN METHODS function reverseString(text) { return text.split("").reverse().join(""); } // CHAINING BUILT-IN METHODS USING ES6 function reverseString(text) { return [...text].reverse().join(''); } // USING A FOR LOOP function reverseString(text) { let result = ""; for (let i = text.length - 1; i >= 0; i--) { result += text[i]; } return result; } // USING A FOR..OF LOOP IN ES6 function reverseString(text) { let result = ""; for (let char of text) { result = char + result } return result; } // RECURSIVE METHOD function reverseString(text) { if (text === "") { return "" } else { return reverseString(text.substr(1)) + text[0] } } // USING .REDUCE() function reverseString(text) { return text.split("").reduce((acc, char) => char + acc); } ================================================ FILE: Beginner/reverseString/index-START.js ================================================ /* CHALLENGE Given a string of text, write an algorithm that returns the text received in a reversed format. E.g reverseString('algorithms') // should return 'smhtirogla' */ function reverseString(text) { // Code goes here } module.exports = reverseString ================================================ FILE: Beginner/reverseString/test.js ================================================ const reverseString = require('./index-START') test('reverseString is a function', () => { expect(typeof reverseString).toEqual('function'); }); test('reverses a string of text', () => { expect(reverseString('aeiou')).toEqual('uoiea'); }); test('reverses a string containing numbers', () => { expect(reverseString('123456789')).toEqual('987654321'); }); test('reverses a string containing mixed case characters', () => { expect(reverseString('AsDfGhJkL')).toEqual('LkJhGfDsA'); }); ================================================ FILE: Beginner/searchReplace/index-SOLUTION.js ================================================ ================================================ FILE: Beginner/searchReplace/index-START.js ================================================ ================================================ FILE: Beginner/searchReplace/test.js ================================================ ================================================ FILE: Beginner/vowelsCounter/index-SOLUTION.js ================================================ // ITERATIVE APPROACH const vowels = ["a", "e", "i", "o", "u"] function vowelsCounter(text) { // Initialize counter let counter = 0; // Loop through text to test if each character is a vowel for (let letter of text.toLowerCase()) { if (vowels.includes(letter)) { counter++ } } // Return number of vowels return counter } // REGULAR EXPRESSIONS function vowelsCounter(text) { // Search text with Regex and store all matching instances let matchingInstances = text.match(/[aeiou]/gi); // Check if matching instances exist then calculate length if (matchingInstances) { // Return number of vowels return matchingInstances.length } else { return 0 } } ================================================ FILE: Beginner/vowelsCounter/index-START.js ================================================ /* CHALLENGE Given a string of text, return the number of vowels found within the text e.g vowelsCounter('anehizxcv') // will return 3 */ function vowelsCounter(text) { // Code goes here } module.exports = vowelsCounter; ================================================ FILE: Beginner/vowelsCounter/test.js ================================================ const vowelsCounter = require('./index-START'); test('vowelsCounter is a function', () => { expect(typeof vowelsCounter).toEqual('function'); }); test('returns the number of vowels found', () => { expect(vowelsCounter('aeiou')).toEqual(5); }); test('returns the number of vowels found when string is capitalized', () => { expect(vowelsCounter('AEIOU')).toEqual(5); }); test('returns the number of vowels found when all alphabets are passed in', () => { expect(vowelsCounter('abcdefghijklmnopqrstuvwxyz')).toEqual(5); }); test('returns the number of vowels found when string has mixed capitalization', () => { expect(vowelsCounter('Abcdegfizzjbhso')).toEqual(4); }); ================================================ FILE: Beginner/whereIBelong/index-SOLUTION.js ================================================ // ITERATING AND COMPARING WITH A FORLOOP(BY FINDING THE IMMEDIATE LARGER VALUE) function whereIBelong(arr, num) { arr.sort((a, b) => { return a - b }) for (var i = 0; i < arr.length; i++) { if (arr[i] >= num) { return i } } return arr.length } // ITERATING AND COMPARING WITH A FORLOOP(BY COUNTING ALL SMALLER VALUES) function whereIBelong(arr, num) { var counter = 0 for (i = 0; i < arr.length; i++) { if (num > arr[i]) { counter++ } } return counter } // USING A WHILE LOOP function whereIBelong(arr, num) { arr.sort((a, b) => { return a - b }) let counter = 0; while (num > arr[counter]) { counter++ } return counter } // FINDING THE NUMBER'S INDEX IN THE ARRAY function whereIBelong(arr, num) { arr.push(num) arr.sort((a, b) => a - b) return arr.indexOf(num) } ================================================ FILE: Beginner/whereIBelong/index-START.js ================================================ /* Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number. E.g whereIBelong([1,2,3,4], 1.5) // should return 1 because it is greater than 1(index 0), but less than 2(index 1). */ function whereIBelong(arr, num) { // Code goes here } module.exports = whereIBelong ================================================ FILE: Beginner/whereIBelong/test.js ================================================ const whereIBelong = require('./index-START'); test('whereIBelong is a function', () => { expect(typeof whereIBelong).toEqual('function'); }); test('returns the appropriate index', () => { expect(whereIBelong([1,2,3,4], 1.5)).toEqual(1); }); test('returns the index of the specified number', () => { expect(whereIBelong([10, 20, 30, 40, 50], 30)).toEqual(2); }); test('returns the index even with an empty array', () => { expect(whereIBelong([], 1)).toEqual(0); }); ================================================ FILE: README.md ================================================ # js-algorithms-demo- Demo repository for JS Algorithms Course ================================================ FILE: package.json ================================================ { "name": "js-algorithms", "version": "1.0.0", "description": "sample course setup", "main": "index.js", "scripts": { "test": "jest" }, "author": "Obosi Philip", "license": "ISC", "devDependencies": { "jest": "^23.6.0" } }