├── day20-Add two numbers.js ├── day49-Is this a triangle?.js ├── day37-Tell if its a leap year.js ├── day46-A Needle in the Haystack.js ├── day42-Sum of two lowest positive integers.js ├── day47-Isograms.js ├── day19-Resistor Color map.js ├── day09-check if an object is empty or not.js ├── day36-Rna Transcription.js ├── day21-Union of Two Arrays.js ├── day33-print unique values from an array.js ├── day02-reverse a string.js ├── day25-Stop gninnipS My sdroW.js ├── day27-Vowel Count.js ├── day03-reverse a given integer number.js ├── day01-random number in the given range.js ├── day26-Find the odd int.js ├── day32-find the greatest common divisor.js ├── day44-Count the divisors of a number.js ├── day35-get nth largest element from an unsorted array..js ├── day45-Find The Parity Outlier.js ├── day50-Get the Middle Character.js ├── day31-Find the Factorial of a Number.js ├── day11-N-th value of the Fibonacci sequence.js ├── day07-regular expression to validate the Indian mobile number.js ├── day28-WeIrD StRiNg CaSe.js ├── day22-Unique In Order.js ├── day06-truncate string to a certain number of words.js ├── day18-Calculate Grains on a given square on a chessboard.js ├── day41-Categorize New Member.js ├── day40-Vehicle Purchase.js ├── day10-remove array element based on object property.js ├── day05-count of characters between the first and last.js ├── day30-Mexican Wave.js ├── day29-Mumbling.js ├── day23-Equal Sides Of An Array.js ├── day15-Determine if a sentence is a pangram.js ├── day24-Write Number in Expanded Form.js ├── day38-Luhn algorithm.js ├── day08-difference between two dates as number of days.js ├── day16-Ask the Bob.js ├── day14-one base to another asked base.js ├── day17-Longest Consecutive Sequence.js ├── day34-most frequent item of an array.js ├── day43-Highest Scoring Word.js ├── day04-convert the time input given in 12 hours format to 24 hours format.js ├── day48-Human readable duration format.js ├── day13-given seconds to space age.js ├── day39-Mixed Juices.js └── day12-spell out the given number in English..js /day20-Add two numbers.js: -------------------------------------------------------------------------------- 1 | const addTwoNumbers = (a, b) => { 2 | return a+b 3 | } 4 | -------------------------------------------------------------------------------- /day49-Is this a triangle?.js: -------------------------------------------------------------------------------- 1 | //Is this a triangle? 2 | 3 | function isTriangle(a, b, c) { 4 | if((a+b > c)&&(a+c>b)&&(b+c)>a) return true 5 | return false 6 | } -------------------------------------------------------------------------------- /day37-Tell if its a leap year.js: -------------------------------------------------------------------------------- 1 | //Tell if its a leap year 2 | 3 | const isLeap = (year) => { 4 | if(year%100 === 0) return false 5 | else if (year%4 === 0 || year%400 === 0) return true 6 | return false 7 | } -------------------------------------------------------------------------------- /day46-A Needle in the Haystack.js: -------------------------------------------------------------------------------- 1 | //A Needle in the Haystack 2 | 3 | function findNeedle(haystack) { 4 | const position = haystack.indexOf('needle') 5 | return 'found the needle at position ' + position 6 | } -------------------------------------------------------------------------------- /day42-Sum of two lowest positive integers.js: -------------------------------------------------------------------------------- 1 | //Sum of two lowest positive integers 2 | 3 | function sumTwoSmallestNumbers(numbers) { 4 | const sortedArr = numbers.sort((a,b)=> a-b) 5 | return sortedArr[0]+sortedArr[1] 6 | } -------------------------------------------------------------------------------- /day47-Isograms.js: -------------------------------------------------------------------------------- 1 | //Isograms 2 | 3 | function isIsogram(str) { 4 | const newStr = str.toLowerCase() 5 | const uniqueArr = new Set(newStr) 6 | if(newStr.length === uniqueArr.size) return true 7 | return false 8 | } 9 | -------------------------------------------------------------------------------- /day19-Resistor Color map.js: -------------------------------------------------------------------------------- 1 | //Resistor Color map 2 | 3 | const bandColors = ['black','brown','red','orange','yellow','green','blue','violate','grey','white'] 4 | 5 | const colorCode = (color) => { 6 | return bandColors.indexOf(color) 7 | } 8 | -------------------------------------------------------------------------------- /day09-check if an object is empty or not.js: -------------------------------------------------------------------------------- 1 | //Write a function to check if an object is empty or not in javaScript? 2 | 3 | const obj = { key: 1 }; 4 | 5 | function isEmpty(obj) { 6 | return !Object.keys(obj).length 7 | } 8 | 9 | console.log(`is empty object: ${isEmpty(obj)}`) -------------------------------------------------------------------------------- /day36-Rna Transcription.js: -------------------------------------------------------------------------------- 1 | //Rna Transcription 2 | 3 | const DTR_Obj = { 4 | G:'C', 5 | C:'G', 6 | T:'A', 7 | A:'U' 8 | } 9 | 10 | const transcription = (dna) => { 11 | const RNA = dna.split('').map(data => DTR_Obj[data]).join('') 12 | return RNA 13 | } -------------------------------------------------------------------------------- /day21-Union of Two Arrays.js: -------------------------------------------------------------------------------- 1 | //Union of Two Arrays 2 | 3 | const unionOfArrays = (arr1, arr2) => { 4 | const uniqueElements = new Set([...arr1, ...arr2]) 5 | 6 | return [...uniqueElements]; 7 | }; 8 | 9 | console.log(`The union is ${unionOfArrays([1, 2, 34, 45, 3], [3, 24, 21])}`); 10 | -------------------------------------------------------------------------------- /day33-print unique values from an array.js: -------------------------------------------------------------------------------- 1 | //Write a program to print unique values from an array 2 | 3 | function set(arrOfNum) { 4 | const uniqueValues = new Set(arrOfNum) 5 | return [...uniqueValues] 6 | } 7 | 8 | const arrOfNum = [1, 2, 2, 4, 5, 6, 6]; 9 | 10 | console.log("result is + " + set(arrOfNum)); -------------------------------------------------------------------------------- /day02-reverse a string.js: -------------------------------------------------------------------------------- 1 | //Write a program to reverse a string 2 | 3 | const str = "JavaScript is awesome" 4 | 5 | function reverseAString(str) { 6 | const reversedStr = str.split('').reverse().join('') 7 | 8 | return reversedStr 9 | } 10 | 11 | console.log(`Reversed string is: ${reverseAString(str)}`) -------------------------------------------------------------------------------- /day25-Stop gninnipS My sdroW.js: -------------------------------------------------------------------------------- 1 | //Stop gninnipS My sdroW! 2 | 3 | function spinWords(string) { 4 | const reversedStr = string.split(' ').map(item => { 5 | if(item.length >= 5) return item.split('').reverse().join('') 6 | return item 7 | }).join(' ') 8 | 9 | return reversedStr 10 | } 11 | -------------------------------------------------------------------------------- /day27-Vowel Count.js: -------------------------------------------------------------------------------- 1 | //Vowel Count 2 | 3 | const vowels = 'aeiou' 4 | 5 | function getCount(str) { 6 | let vowelsCount = 0; 7 | 8 | str.toLowerCase().split('').forEach(char => { 9 | if(vowels.includes(char)) vowelsCount++; 10 | }) 11 | 12 | return vowelsCount; 13 | } 14 | 15 | console.log(getCount("abracadabra")); -------------------------------------------------------------------------------- /day03-reverse a given integer number.js: -------------------------------------------------------------------------------- 1 | //Write a program to reverse a given integer number 2 | 3 | const num = 3849; 4 | 5 | function reverseGivenInteger(num) { 6 | const reversedNum = num.toString().split('').reverse().join('') 7 | 8 | return Number(reversedNum) 9 | } 10 | 11 | console.log(`Reversed integer is: ${reverseGivenInteger(num)}`) -------------------------------------------------------------------------------- /day01-random number in the given range.js: -------------------------------------------------------------------------------- 1 | //Function which returns a random number in the given range 2 | 3 | function randomNumberGeneratorInRange(rangeStart, rangeEnd) { 4 | const randomNumber = Math.floor(Math.random()*(rangeEnd-rangeStart)) 5 | 6 | return rangeStart + randomNumber 7 | } 8 | 9 | console.log(`My random number: ${randomNumberGeneratorInRange(5, 100)}`) -------------------------------------------------------------------------------- /day26-Find the odd int.js: -------------------------------------------------------------------------------- 1 | //Find the odd int 2 | 3 | function findOdd(arr) { 4 | let oddInt = undefined 5 | const uniqueElements = [...new Set([...arr])] 6 | 7 | uniqueElements.forEach(el => { 8 | const elCount = arr.filter(item => item === el).length 9 | if(elCount%2 !== 0) oddInt = el 10 | }) 11 | 12 | return oddInt; 13 | } -------------------------------------------------------------------------------- /day32-find the greatest common divisor.js: -------------------------------------------------------------------------------- 1 | //Write a program to find the greatest common divisor (gcd) of two positive numbers. 2 | 3 | function gcd(a, b) { 4 | while(b) { 5 | var t = b; 6 | b = a % b; 7 | a = t; 8 | } 9 | return a 10 | } 11 | 12 | const a = 2154 13 | const b = 458 14 | 15 | console.log("The GCD of " + a + " ", b + " is " + gcd(a, b)); -------------------------------------------------------------------------------- /day44-Count the divisors of a number.js: -------------------------------------------------------------------------------- 1 | //Count the divisors of a number 2 | 3 | function getDivisorsCnt(num) { 4 | const arr = Array.from({length:num}) 5 | const outputCountArr = arr.map((item,index) => { 6 | if(num%(index+1) === 0) return true 7 | return false 8 | }).filter(item => item) 9 | 10 | return outputCountArr.length 11 | } 12 | -------------------------------------------------------------------------------- /day35-get nth largest element from an unsorted array..js: -------------------------------------------------------------------------------- 1 | //Write a JavaScript function to get nth largest element from an unsorted array. 2 | 3 | function nthlargest(arr, highest) { 4 | const sortedArr = arr.sort((a,b)=> a-b) 5 | return sortedArr[highest] 6 | } 7 | 8 | const arr = [43, 56, 23, 89, 88, 90, 99, 652]; 9 | const highest = 4; 10 | 11 | console.log(nthlargest(arr, highest)); -------------------------------------------------------------------------------- /day45-Find The Parity Outlier.js: -------------------------------------------------------------------------------- 1 | //Find The Parity Outlier 2 | 3 | function findOutlier(integers) { 4 | const oddArr = [] 5 | const evenArr = [] 6 | 7 | integers.forEach(item => { 8 | if(item%2 === 0) evenArr.push(item) 9 | else oddArr.push(item) 10 | }) 11 | 12 | if(oddArr.length > evenArr.length) return evenArr[0] 13 | return oddArr[0] 14 | } -------------------------------------------------------------------------------- /day50-Get the Middle Character.js: -------------------------------------------------------------------------------- 1 | //Get the Middle Character 2 | 3 | function getMiddle(s) { 4 | const strLen = s.length 5 | let position = 0 6 | if(strLen%2 !== 0) { 7 | position = Math.floor(strLen/2) 8 | return s.charAt(position) 9 | } else { 10 | position = strLen/2 11 | return s.charAt(position-1) + s.charAt(position) 12 | } 13 | } -------------------------------------------------------------------------------- /day31-Find the Factorial of a Number.js: -------------------------------------------------------------------------------- 1 | //Write a Program to Find the Factorial of a Number 2 | 3 | function factorial(n) { 4 | let factorial = 1; 5 | if(n===0) return factorial; 6 | else if(n<0) return undefined; 7 | return Array.from({length:n}).reduce((acc,curr,index)=>acc*(index+1),factorial) 8 | } 9 | 10 | let n = 4; 11 | console.log("The factorial of " + n + " is " + factorial(n)); -------------------------------------------------------------------------------- /day11-N-th value of the Fibonacci sequence.js: -------------------------------------------------------------------------------- 1 | //Return the N-th value of the Fibonacci sequence 2 | 3 | function getFibNum(n){ 4 | if(n<=0) return 0 5 | if(n===1) return 0 6 | if(n===2) return 1 7 | else return getFibNum(n-1) + getFibNum(n-2) 8 | } 9 | 10 | function fibonacci(n) { 11 | return getFibNum(n+1) 12 | } 13 | 14 | console.log(`fibonacci value at position 5: ${fibonacci(5)}`) -------------------------------------------------------------------------------- /day07-regular expression to validate the Indian mobile number.js: -------------------------------------------------------------------------------- 1 | //Create a regular expression to validate if the given input is valid Indian mobile number or not 2 | 3 | const number = '+919876543210'; 4 | 5 | function validateMobile(number) { 6 | const regEx = /^(\+91|0)?( )?(\d{10})$/ 7 | return regEx.test(number) 8 | } 9 | 10 | console.log(`is a valid Indian mobile number: ${validateMobile(number)}`) -------------------------------------------------------------------------------- /day28-WeIrD StRiNg CaSe.js: -------------------------------------------------------------------------------- 1 | //WeIrD StRiNg CaSe 2 | 3 | function toWeirdCase(string) { 4 | const weirdStr = string.split('').map((char,index) => { 5 | if(index%2 === 0) return char.toUpperCase() 6 | return char.toLowerCase() 7 | }).join('') 8 | 9 | return weirdStr; 10 | } 11 | 12 | console.log( 13 | `The weird case of ${"A test case"} is ${toWeirdCase("A test case")}` 14 | ); -------------------------------------------------------------------------------- /day22-Unique In Order.js: -------------------------------------------------------------------------------- 1 | //Unique In Order 2 | 3 | let uniqueInOrder = (iterable) => { 4 | //iterable can be a string or an array 5 | const array = [...iterable] 6 | const uniqueOrderedArr = [] 7 | 8 | for(let value of array){ 9 | if(value !== uniqueOrderedArr[uniqueOrderedArr.length-1]){ 10 | uniqueOrderedArr.push(value) 11 | } 12 | } 13 | 14 | return uniqueOrderedArr 15 | }; -------------------------------------------------------------------------------- /day06-truncate string to a certain number of words.js: -------------------------------------------------------------------------------- 1 | //Write a function to truncate a string to a certain number of words 2 | 3 | const str = 'JavaScript is simple but not easy to master'; 4 | const wordLimit = 3 5 | 6 | function truncateWithWordLimit(str, wordLimit) { 7 | const truncateWord = str.split(' ').slice(0,wordLimit).join(' ') 8 | 9 | return truncateWord 10 | } 11 | 12 | console.log(`Truncated string: ${truncateWithWordLimit(str, wordLimit)}`) -------------------------------------------------------------------------------- /day18-Calculate Grains on a given square on a chessboard.js: -------------------------------------------------------------------------------- 1 | //Calculate Grains on a given square on a chessboard 2 | 3 | const totalGrains = () => { 4 | const summationOfAllGrain = (2**64) - 1 5 | return summationOfAllGrain 6 | } 7 | 8 | const grainsOn = (input) => { 9 | const grainCount = 2**(input-1) 10 | return grainCount 11 | } 12 | 13 | console.log(`Grains on 5th square: ${grainsOn(5)}`) 14 | console.log(`Total grains on the Chess Board: ${totalGrains()}`) -------------------------------------------------------------------------------- /day41-Categorize New Member.js: -------------------------------------------------------------------------------- 1 | //Categorize New Member 2 | 3 | function openOrSenior(data) { 4 | const outputArr = data.reduce((acc,curr)=>{ 5 | if(curr[0] >= 55 && curr[1] > 7) acc.push('Senior') 6 | else acc.push('Open') 7 | return acc 8 | },[]) 9 | 10 | return outputArr 11 | } 12 | 13 | let output = openOrSenior([ 14 | [45, 12], 15 | [55, 21], 16 | [19, -2], 17 | [104, 20], 18 | ]); 19 | 20 | console.log(output); -------------------------------------------------------------------------------- /day40-Vehicle Purchase.js: -------------------------------------------------------------------------------- 1 | //Vehicle Purchase 2 | 3 | const needsLicense = (kind) => { 4 | const kindsArr = ['car','truck'] 5 | return kindsArr.includes(kind) 6 | } 7 | 8 | const chooseVehicle = (option1, option2) => { 9 | return [option1,option2].sort()[0] + ' is clearly the better choice.' 10 | } 11 | 12 | const calculateResellPrice = (originalPrice, age) => { 13 | if(age > 10) return originalPrice*.5 14 | else if (age >= 3) return originalPrice*.7 15 | return originalPrice*.8 16 | } -------------------------------------------------------------------------------- /day10-remove array element based on object property.js: -------------------------------------------------------------------------------- 1 | //Write a function to remove array element based on object property? 2 | 3 | const array = [ 4 | { field: "id", operator: "eq" }, 5 | { field: "cStatus", operator: "eq" }, 6 | { field: "money", operator: "eq" }, 7 | ]; 8 | 9 | const filterField = "money" 10 | 11 | function removeArrayElement(filterField) { 12 | return array.filter(item => item.field !== filterField) 13 | } 14 | 15 | console.log(`filtered array: ${removeArrayElement(filterField)}`) -------------------------------------------------------------------------------- /day05-count of characters between the first and last.js: -------------------------------------------------------------------------------- 1 | //Write a function which accepts a string argument and returns the count of characters between the first and last character 'X' 2 | 3 | const str = 'XeroX'; 4 | 5 | function getTheGapX(str) { 6 | const firstIndex = str.indexOf('X') 7 | const lastIndex = str.lastIndexOf('X') 8 | if(firstIndex === -1) return -1 9 | 10 | const gapBeetweenX = lastIndex - firstIndex 11 | return gapBeetweenX 12 | } 13 | 14 | console.log(`Gap between the X's: ${getTheGapX(str)}`) -------------------------------------------------------------------------------- /day30-Mexican Wave.js: -------------------------------------------------------------------------------- 1 | //Mexican Wave 2 | 3 | String.prototype.replaceAt = function(index, replacement) { 4 | return this.substr(0, index) + replacement + this.substr(index + replacement.length); 5 | } 6 | 7 | function wave(str) { 8 | const waveArr = str.split('').reduce((totalWave,currChar,index) => { 9 | if(currChar===' ') return totalWave; 10 | totalWave.push(str.replaceAt(index, currChar.toUpperCase())); 11 | return totalWave 12 | },[]) 13 | 14 | return waveArr 15 | } 16 | 17 | console.log(wave("hello")); -------------------------------------------------------------------------------- /day29-Mumbling.js: -------------------------------------------------------------------------------- 1 | //Mumbling 2 | 3 | function accum(s) { 4 | const mumbledStr = s.split('').reduce((acc,curr,currIndex) => { 5 | if(currIndex === 0) return curr.toUpperCase() 6 | 7 | let charArr = '' 8 | let n = currIndex+1; 9 | 10 | while(n>0){ 11 | if(n===(currIndex+1)) charArr += curr.toUpperCase() 12 | else charArr += curr.toLowerCase(); 13 | n--; 14 | } 15 | 16 | return acc + '-' + charArr 17 | },'') 18 | 19 | return mumbledStr 20 | } -------------------------------------------------------------------------------- /day23-Equal Sides Of An Array.js: -------------------------------------------------------------------------------- 1 | //Equal Sides Of An Array 2 | 3 | const summationOfArr = (slicedArray) => { 4 | return slicedArray.reduce((a, b) => a + b, 0) 5 | } 6 | 7 | function findEvenIndex(arr) { 8 | let evenIndex = -1; 9 | for(const index in arr){ 10 | const numIndex = Number(index) 11 | const sumFromtheStart = summationOfArr(arr.slice(0,numIndex)) 12 | const sumFromtheEnd = summationOfArr(arr.slice(numIndex+1)) 13 | if(sumFromtheStart === sumFromtheEnd) return numIndex 14 | } 15 | return evenIndex 16 | } -------------------------------------------------------------------------------- /day15-Determine if a sentence is a pangram.js: -------------------------------------------------------------------------------- 1 | //Determine if a sentence is a pangram 2 | 3 | const isPangram = (input) => { 4 | const str = input.toLowerCase(); 5 | const { length } = str; 6 | const alphabets = 'abcdefghijklmnopqrstuvwxyz'; 7 | const alphaArr = alphabets.split(''); 8 | 9 | for(let i = 0; i < length; i++){ 10 | const el = str[i]; 11 | const index = alphaArr.indexOf(el); 12 | if(index !== -1){ 13 | alphaArr.splice(index, 1); 14 | }; 15 | }; 16 | 17 | return !alphaArr.length; 18 | } 19 | -------------------------------------------------------------------------------- /day24-Write Number in Expanded Form.js: -------------------------------------------------------------------------------- 1 | //Write Number in Expanded Form 2 | 3 | const generateZero = (n) => { 4 | let zeros = '' 5 | while(n>0){ 6 | zeros += '0' 7 | n-- 8 | } 9 | return zeros 10 | } 11 | 12 | function expandedForm(num) { 13 | const numToStr = String(num) 14 | const value = numToStr.split('').reduce((acc, curr, index)=>{ 15 | if(index === 0) return curr + generateZero(numToStr.length - (index+1)) 16 | return acc + '+' + curr + generateZero(numToStr.length - (index+1)) 17 | },'') 18 | return value 19 | } -------------------------------------------------------------------------------- /day38-Luhn algorithm.js: -------------------------------------------------------------------------------- 1 | //Luhn algorithm 2 | 3 | const valid = (string) => { 4 | const newStr = string.replaceAll(' ','') 5 | const numberStrArr = newStr.split('').reverse() 6 | const validCardNumArr = numberStrArr.map((digit,index)=>{ 7 | if((index+1)%2 === 0){ 8 | let newDigit = digit*2 9 | if(newDigit>9) newDigit -= 9 10 | return +newDigit 11 | } 12 | return +digit 13 | }) 14 | const sumOfArr = validCardNumArr.reduce((acc,curr)=>acc+curr,0) 15 | console.log(sumOfArr) 16 | return sumOfArr%10 === 0? true:false 17 | } -------------------------------------------------------------------------------- /day08-difference between two dates as number of days.js: -------------------------------------------------------------------------------- 1 | //Write a function which accepts two valid dates and returns the difference between them as number of days 2 | 3 | const DAY_IN_MILLISECONDS = 1000 * 60 * 60 * 24; 4 | 5 | function getDaysBetweenDates(dateText1, dateText2) { 6 | const dateMill1 = +new Date(dateText1); 7 | const dateMill2 = +new Date(dateText2); 8 | 9 | const diffInMill = dateMill2 - dateMill1 10 | const diffInDays = diffInMill/DAY_IN_MILLISECONDS 11 | return diffInDays 12 | } 13 | 14 | console.log(`Days difference: ${getDaysBetweenDates('10/15/2020', '12/1/2020')}`) -------------------------------------------------------------------------------- /day16-Ask the Bob.js: -------------------------------------------------------------------------------- 1 | //Ask the Bob 2 | 3 | const questionRegx = new RegExp(/[\w\s,:;]*[?]/); 4 | const capitalYellRegx = new RegExp(/[A-Z\s,:;]/); 5 | const yellQuestionRegx = new RegExp(/[A-Z\s,:;]*[?]/); 6 | const addressRegx = new RegExp(/[bob]/gi) 7 | 8 | function hey(message) { 9 | if(questionRegx.test(message)) return 'Sure.' 10 | else if(capitalYellRegx.test(message)) return 'Whoa, chill out!' 11 | else if(yellQuestionRegx.test(message)) return 'Calm down, I know what I\'m doing!' 12 | else if(addressRegx.test(message)) return 'Fine. Be that way!' 13 | 14 | return 'Whatever.' 15 | } 16 | -------------------------------------------------------------------------------- /day14-one base to another asked base.js: -------------------------------------------------------------------------------- 1 | //Convert given array of digits of a base to another asked base 2 | 3 | /** 4 | * 5 | * @param {number[]} digits Array of valid digits of baseA 6 | * @param {number} baseA base a 7 | * @param {number} baseB base b in which digits are to be converted 8 | * @returns {number[]} Array of valid digits of baseB 9 | */ 10 | 11 | 12 | const convertDigitsToAskedBase = (digits, baseA, baseB) => { 13 | const ArrToNum = digits.join('') 14 | const ArrNumToDecFromBaseA = parseInt(ArrToNum,baseA) 15 | const decToBaseBArr = ArrNumToDecFromBaseA.toString(baseB).split('').map(item => parseInt(item,baseB)) 16 | 17 | return decToBaseBArr 18 | } 19 | -------------------------------------------------------------------------------- /day17-Longest Consecutive Sequence.js: -------------------------------------------------------------------------------- 1 | //Longest Consecutive Sequence 2 | 3 | /** 4 | * 5 | * @param {number[]} inputArray Array of numbers 6 | */ 7 | 8 | const longestConsecutiveSequence = (inputArray) => { 9 | let count = 0 10 | const set = new Set(inputArray); 11 | const sortedArray = [...set].sort((a,b)=>a-b) 12 | 13 | for(const [index, el] of sortedArray.entries()){ 14 | if(index === 0) { 15 | count++; 16 | continue; 17 | }; 18 | if(sortedArray[index] === sortedArray[index-1]+1) { 19 | count++; 20 | continue; 21 | } 22 | break 23 | } 24 | 25 | return count 26 | } 27 | -------------------------------------------------------------------------------- /day34-most frequent item of an array.js: -------------------------------------------------------------------------------- 1 | //Write a program to find the most frequent item of an array 2 | 3 | function mostFreq(arr) { 4 | const frqCountObj = arr.reduce((acc,curr)=>{ 5 | if(acc[curr]) acc[curr] = acc[curr] + 1; 6 | else acc[curr] = 1 7 | return acc; 8 | },{}) 9 | 10 | const mFrqKey = Object.keys(frqCountObj).reduce((accKey,currKey)=>{ 11 | if(!accKey) return currKey 12 | else if((frqCountObj[accKey] < frqCountObj[currKey])) 13 | return currKey 14 | return accKey 15 | },'') 16 | return `${mFrqKey} ${frqCountObj[mFrqKey]}` 17 | } 18 | 19 | const arr = [1, 2, 2, 4, 5, 6, 6]; 20 | 21 | console.log(mostFreq(arr)); -------------------------------------------------------------------------------- /day43-Highest Scoring Word.js: -------------------------------------------------------------------------------- 1 | //Highest Scoring Word 2 | 3 | const positionArr=['','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 4 | 5 | function high(x) { 6 | const arrOfWord = x.split(' ') 7 | const scoresOfWord = arrOfWord.map(item => { 8 | return item.split('').reduce((acc,curr) => 9 | acc + positionArr.indexOf(curr),0) 10 | }) 11 | 12 | const highestScoredIndex = scoresOfWord.reduce((accIndex,currItem,currIndex) => { 13 | if((currIndex > 0) && (scoresOfWord[accIndex] < currItem)) { 14 | return currIndex 15 | } 16 | return accIndex 17 | },0) 18 | 19 | return arrOfWord[highestScoredIndex] 20 | } -------------------------------------------------------------------------------- /day04-convert the time input given in 12 hours format to 24 hours format.js: -------------------------------------------------------------------------------- 1 | //Write a function which can convert the time input given in 12 hours format to 24 hours format 2 | 3 | const time = '12:10AM'; 4 | 5 | const getFormettedString = (string) => { 6 | if(string.length > 1) return string 7 | return `0${string}` 8 | } 9 | 10 | function convertTo24HrsFormat(time) { 11 | const isAM = time.includes('AM') ? true : false 12 | const timeWithoutAmPm = time.replace(/AM/gi,'').replace(/PM/gi,'') 13 | const timeArray = timeWithoutAmPm.split(':') 14 | 15 | const hours = isAM ? timeArray[0] == '12' ? '00': getFormettedString(timeArray[0]) : timeArray[0] == '12' ? timeArray[0] : String((Number(timeArray[0])+12)) 16 | const minutes = getFormettedString(timeArray[1]) 17 | 18 | const formattedTime = `${hours}:${minutes}` 19 | 20 | return formattedTime 21 | } 22 | 23 | console.log(`Converted time: ${convertTo24HrsFormat(time)}`) -------------------------------------------------------------------------------- /day48-Human readable duration format.js: -------------------------------------------------------------------------------- 1 | //Human readable duration format 2 | 3 | const hoursInSec = 60*60 4 | const minutesInSec = 60 5 | const durationStrArr = ['hour','minute','second'] 6 | 7 | function formatDuration(seconds) { 8 | const hours = parseInt(seconds/hoursInSec) 9 | const remainingSeconds = seconds - (hours*hoursInSec) 10 | const minutes = remainingSeconds > 59 ? parseInt(remainingSeconds/minutesInSec) : 0 11 | const Seconds = remainingSeconds < 59 ? remainingSeconds : remainingSeconds - (minutes*minutesInSec) 12 | 13 | const hrdfArr = [hours,minutes,Seconds].reduce((acc,curr,index)=>{ 14 | if(curr !== 0){ 15 | if(curr === 1) acc.push(`${curr} ` + durationStrArr[index]) 16 | else acc.push(`${curr} ` + durationStrArr[index] + 's') 17 | } 18 | return acc 19 | },[]) 20 | 21 | if(hrdfArr.length === 3) 22 | return hrdfArr[0] + ', ' + hrdfArr.slice(1).join(' and ') 23 | else return hrdfArr.join(' and ') 24 | } -------------------------------------------------------------------------------- /day13-given seconds to space age.js: -------------------------------------------------------------------------------- 1 | //Convert given seconds to space age on all planets of our solar system 2 | 3 | const spaceAge = (seconds) => { 4 | const secondsInDays = (((seconds/60)/60)/24) 5 | const earthYearInDyas = 365.25 6 | const yearsInAllPlanets = { 7 | Mercury: 0, 8 | Venus: 0, 9 | Earth: 0, 10 | Mars: 0, 11 | Jupiter: 0, 12 | Saturn: 0, 13 | Uranus: 0, 14 | Neptune: 0, 15 | } 16 | 17 | const earthYearInDays = { 18 | Mercury: earthYearInDyas*0.2408467, 19 | Venus: earthYearInDyas*0.61519726, 20 | Earth: earthYearInDyas, 21 | Mars: earthYearInDyas*1.8808158, 22 | Jupiter: earthYearInDyas*11.862615, 23 | Saturn: earthYearInDyas*29.447498, 24 | Uranus: earthYearInDyas*84.016846, 25 | Neptune: earthYearInDyas*164.79132, 26 | } 27 | 28 | Object.keys(yearsInAllPlanets).forEach(planet => { 29 | yearsInAllPlanets[planet] = Number((secondsInDays/earthYearInDays[planet]).toFixed(2)) 30 | }) 31 | 32 | return yearsInAllPlanets 33 | } 34 | 35 | console.log(spaceAge(Math.round(Math.random() * 99999999))) -------------------------------------------------------------------------------- /day39-Mixed Juices.js: -------------------------------------------------------------------------------- 1 | //Mixed Juices 2 | 3 | const juiceArr=['Pure Strawberry Joy','Energizer','Green Garden','Tropical Island','All or Nothing'] 4 | const estimatedTimeArr=[0.5,1.5,1.5,3,5] 5 | const defaultTime = 2.5 6 | 7 | 8 | const timeToMixJuice = (name) => { 9 | if(juiceArr.includes(name)) return estimatedTimeArr[juiceArr.indexOf(name)] 10 | return defaultTime 11 | } 12 | 13 | const limePieces = { 14 | small:6, 15 | medium:8, 16 | large:10 17 | } 18 | 19 | const limesToCut = (wedgesNeeded, limes) => { 20 | let limeNum = 0; 21 | let total = 0; 22 | 23 | for(let i=0; i= wedgesNeeded) { 25 | break; 26 | } 27 | limeNum = i + 1; 28 | total += limePieces[limes[i]] 29 | } 30 | 31 | return limeNum 32 | } 33 | 34 | 35 | const remainingOrders = (timeLeft, orders) => { 36 | let totalTime = 0 37 | for(value in orders){ 38 | if(totalTime >= timeLeft) break; 39 | 40 | if(juiceArr.includes(name)) { 41 | totalTime += estimatedTimeArr[juiceArr.indexOf(name)] 42 | } 43 | totalTime += defaultTime 44 | orders.shift() 45 | } 46 | 47 | return orders 48 | } -------------------------------------------------------------------------------- /day12-spell out the given number in English..js: -------------------------------------------------------------------------------- 1 | //Given a number from 0 to 999,999,999,999, spell out that number in English. 2 | 3 | var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen ']; 4 | var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; 5 | 6 | const getWordsOfNumber = (numberString) => { 7 | const n = Number(numberString).toString() 8 | if(n.length > 2) return getWordsOfNumber(n[0]) + 'hundred ' + getWordsOfTwoDigitNumber(n.substr(1,2)) 9 | return a[Number(n)] || b[n[0][1]] 10 | } 11 | 12 | const getWordsOfTwoDigitNumber = (twoDigitNumber) => { 13 | const n = Number(twoDigitNumber).toString() 14 | return (a[Number(n)] || b[n[0]] + (a[n[1]]?`-${a[n[1]]}`:'')) + ''; 15 | } 16 | 17 | const sayNumberInEnglish = (num /* ADD MORE PARAMETERS IF NEEDED */) => { 18 | if ((num = num.toString()).length > 12) return 'overflow'; 19 | n = ('000000000000' + num).substr(-12).match(/^(\d{3})(\d{3})(\d{3})(\d{1})(\d{2})$/); 20 | if (!n) return; 21 | var str = ''; 22 | str += (n[1] != 0) ? getWordsOfNumber(n[1]) + 'billion ' : ''; 23 | str += (n[2] != 0) ? getWordsOfNumber(n[2]) + 'million ' : ''; 24 | str += (n[3] != 0) ? getWordsOfNumber(n[3]) + 'thousand ' : ''; 25 | str += (n[4] != 0) ? getWordsOfNumber(n[4]) + 'hundred ' : ''; 26 | str += (n[5] != 0) ? getWordsOfTwoDigitNumber(n[5]):''; 27 | return str.trimEnd(); 28 | } 29 | 30 | console.log(`${sayNumberInEnglish(3942681)}`) --------------------------------------------------------------------------------