Posts

Showing posts from July, 2021

Junior Developer Central JS Practice Exercise - 22

  Question:  Write a Javascript function that accepts a string as a parameter and counts the number of vowels within the string.  Answer:  function vowelCount (str) {   let vowels = /[aeiou]/gi;   let result = str.match(vowels);   let count = result.length;   return count;       }; > we declare a function 'vowelCount'  > it has one parameter 'str', which is a string > we declare a variable 'vowels' and initialize it with the 5 vowels > the 'g' modifier is used on the 'vowels' variable to perform a global match  > a global match will find all matches and will not stop after finding the first match >  additionally   the 'i' modifier is used  on the 'vowels' variable to perform case insensitive matching > we declare another variable 'result' and initialize it with the result we get when we use the match () method on the 'str' parameter > the match() method searches a string for a ma...

Junior Developer Central JS Practice Exercise - 21

  Question:  Write a Javascript function that returns a passed string with letters in alphabetical order.  Example String:            'javascript'  Example Output:             ' aacijprstv' Answer:  function alphaStr (str) { return str.split('').sort().join('') }            > we declare a function 'alphaStr'  > it has one parameter 'str'  > we use the split ('') method on the string 'str' to split all the characters in an array > we then use the sort() method to sort the characters in alphabetical order > we then use the join('') method to create a string by concatenating all the sorted elements of the array created  > we return this line of code to get our alphabetically sorted string

Junior Developer Central JS Practice Exercise - 20

  Question:  Write a Javascript function that returns true if the provided predicate function returns true for all elements in a collection, false otherwise.  Answer:  function checkFunction(arr, fn) {   for (let i = 0; i < arr.length; i++) {     if (!fn(arr[i])) {       return false;     }   }   return true; } > we declare a function 'checkFunction'  > it has two parameters 'arr' & 'fn'  > we want to return false if 'fn' (which is a function) returns false for even one element in 'arr' (which is an array) > our function should return true if the function 'fn' returns true for all elements in array 'arr' > so in order to check the result of the function 'fn' on each and every element of array 'arr' we use the for loop >  we additionally use the if statement to check the boolean value on each iteration of the for loop > we return false if the condition is met and the loop is t...

Junior Developer Central JS Practice Exercise - 19

  Question:  Write a Javascript program to generate a random hexadecimal color code Answer:  function getRandomColor() {                    let letters = '0123456789ABCDEF'.split('');         let color = '#';         for (var i = 0; i < 6; i++ ) {             color += letters[Math.round(Math.random() * 15)];         }         return color;     } > we declare a function 'getRandomColor'  > it has no parameters > we create a variable 'letters'  > it is a string of 16 characters - '0123456789ABCDEF' > we use the split () method to return an array with 16 array elements > we declare another variable 'color'  > its is a string with only the '#' character > we then create a for loop  >> initialization - before the loop starts we set our variable i = 0 ...

Junior Developer Central JS Practice Exercise - 18

  Question:  Write a Javascript program to convert a comma-separated values (CSV) string to a 2D array. A new line indicates a new row in the array.  for eg.  Input:  const oldString = `abc,def,ghi jkl, mno, pqr stu, vwx, yza`; Output:  0: (3) ["abc", " def", " ghi"] 1: (3) ["jkl", " mno", " pqr"] 2: (3) ["stu", " vwx", " yza"] Answer:  function createArr(str) {   return str.split('\n').map(row => row.split(',')); } > we declare a variable 'createArr'  > it has one parameter 'str'  > to explain this function, we shall use the input example in the question above 'oldString' > we first split the 'str' with the split () method that will return an array of substrings > the split ('\n') method will return a new array which will have three items  > each of these items is a row from the 'oldString' mentioned above >...

Junior Developer Central JS Practice Exercise - 17

  Question:  Write a Javascript program to compare two objects to determine if the first one contains the same properties as the second one (which may also have additional properties) for eg:  const objA = { a: 1, b: 2, c: 1 };  const objB = { a: 1, b: 1, c: 1 }; const objC = { a: 1, b: 1, d: 1 }; Answer:  function comTwoObj (obj1, obj2) { const obj2Keys = Object.keys(obj2);  return Object.keys(obj1).every(key => obj2Keys.includes(key)); } > we declare a function 'comTwoObj'  > it has 2 parameters 'obj1' & 'obj2'  > we want to compare the keys of the two objects 'obj1' & 'obj2'  > we do not want to compare the values, only the keys > in our case the 'keys' are: a, b, c & so on > we want to check if 'obj2' has all the keys of 'obj1'  > 'obj2' can have additional keys as well, for eg: a, b, c, d, e & so on > but it should have all the keys of 'obj1'  > so first we...

Junior Developer Central JS Practice Exercise - 16

  Question:  Given a year, report if it is a leap year.  Answer:  function isLeapYear (year) { const leapYear01 = year;  const leapYear02 = leapYear01 / 4; if (Number.isInteger( leapYear02 )) { return true;  } else {  return false; } } > we declare a function 'isLeapYear'  > it has one parameter 'year'  > leap year has 366 days > leap year comes every 4 years > all leap years are divisible by 4 > hence all the years that are divisible by 4 are 'leap years'  > so first we create a variable 'leapYear01'  > we initialize it with a value that we get in 'year' argument > then we create another variable 'leapYear02'  >  we initialize it with a value that we get by dividing the  'leapYear01' by 4 > we then open an if/else statement > we want to check if the value stored in  'leapYear02' is an integer > an integer is a whole number > an integer is a number that can be written wit...

Junior Developer Central JS Practice Exercise - 15

  Question:  Write a Javascript program to replace the first digit in a string with $ character.  Answer:  function replaceFirstDigit (str) { const newStr = str.replace(/[0-9]/, '$');  console.log (newStr);  } > we declare a function 'replaceFirstDigit'  > it has one parameter 'str' which is a string > we need to replace only the first digit occurrence in the 'str' string with a '$' sign  > we declare a variable 'newStr'  > we initialize it with a value that we get by using the replace method on 'str'  > we use the character class or ''RegExp [0-9] Expression'' to find the digit in 'str'  > we do not use the modifier 'g' as it will search for all the digits > we only want the first occurrence so we will use on '/[0-9]/' & not  '/[0-9]/g' > we use '$' sign as the replacement > we then console.log the 'newStr' variable to get our answer

Junior Developer Central JS Practice Exercise - 14

  Question:  Write a Javascript program to get the largest even number from an array of integers.  Answer:  function largestEven (arr) { const newArr01 = arr;  const newArr02 = newArr01.filter(i => i % 2 === 0);  newArr02.sort((a,b) => b - a);  console.log (newArr02[0]);  } > we declare a function 'largestEven'  > it has one parameter 'arr' which is an array of numbers > we create a variable 'newArr01' and initialize it with value of the 'arr' > we create another variable 'newArr02'  > we initialize it with a value we get by using the filter method & modulo of 2, on 'newArr01' > we then sort the 'newArr02' variable in descending order > we console.log the first index value of the 'newArr02' to get the largest even number

Junior Developer Central JS Practice Exercise - 13

  Question:  Write a Javascript program to check whether a given array of integers is sorted in ascending order.  Answer:  function isAscendingOrder (arr) { for (let i = 0; i < arr.length; i++) { if (arr[i+1] < arr[i]) return false; } return true; } > we declare a function 'isAscending'  > it has one parameter 'arr', which is an array of integers > we have to check if this array of integers is sorted in ascending order or not > so we use the for loop to check if each integer is greater than the following integer > the for loop ensures that our check begins from the first integer to the last > if the integer is greater than the following integer we return 'false'  > because an array of ascending numbers, will have the preceding number lesser than the following number > if that is not the case then we return 'true' once the for loop has finished the iteration and not found any number in the array which is greater than its foll...

Junior Developer Central JS Practice Exercise - 12

  Question:  Write a Javascript program to find the number of even values up to a given number.  Answer:  function evenValue (num) { let evenNum = num; let allVal = [];  let totalEven;  for (let i = 1; i < evenNum; i++) { allVal.push(i); totalEven = allVal.filter(i => i % 2 === 0).length; };  console.log(totalEven); } > we declare a function 'evenValue' > it has one parameter 'num'; which is a number > we have to find out all the even values up to the number provided in 'num'  > so first we create an array of all numbers from 1 to n (or 'num')   >> we declare a variable 'allVal' which is an array >> we use a for loop to push all the numbers up to n (or 'num') > secondly we use the filter method on 'allVal' to create an array of even numbers >> we declare another variable 'totalEven'  >> it is initialized with a value we get by using the filter method on 'allVal'  >...

Junior Developer Central JS Practice Exercise - 11

  Question:  Write a Javascript program to find the number of even digits in an array of integers.  Answer:  function evenArr (arr) { let regArr = arr;  let evenArrL = regArr.filter(i => i % 2 === 0).length;  console.log(evenArrL);  } > we declare a function 'evenArr'  > it has one parameter 'arr'  > we create a variable 'regArr' > it is initialized with the parameter 'arr' which is an array of integers > we create another variable 'evenArrL' > we initialize it with the value we get when we use the filter method on 'regArr'  > we want to filter all the even numbers of the 'regArr'  > to do that we use the modulo / remainder operator  > however we only need to know the number of even digits  > so we add the 'length' method to get the total number of even digits in the array > finally we console.log our answer

Junior Developer Central JS Practice Exercise - 10

  Question:  Write a Javascript program to check if a given string contains 2 to 4 occurrences of a specified character.  Answer:  function countChar (str, char) { let arr01 = str.split('');  let arr02 = arr01.filter(ch => ch === char).length;  if (arr02 >= 2 && arr02 <= 4) { return true;  } else { return false; } } > we declare a function 'countChar'  > it has 2 parameters 'str' & 'char' > we create a variable 'arr01' & initialize it with a value we get by splitting the 'str'  > 'arr01' is an array as we have split the 'str' elements into an array of characters > we create another variable 'arr02' and use the filter method on 'arr01'  > we want to filter out all the elements that are equal to the character we need to find > however we do not need an array of all the similar characters  > we need to know only the number of times it has occurred in the string ...

Junior Developer Central JS Practice Exercise - 09

  Question:  Given two values, write a Javascript program to find out which one is nearest to 100.  Answer:  function nearHund (num1, num2) { if (num1 > num2 && num1 <= 100) { return num1;  } else if (num1 < num2 && num2 <= 100) { return num2;  } else if (num1 > num2 && num2 > 100) { return num2;  } else if (num1 < num2 && num1 > 100) { return num1; } else { return num1; } } > we declare a function 'nearHund' > it has two parameters 'num1' and 'num2' > we open if / else statements to check if the numbers are near the number '100'  > there are mainly 5 possibilities that need to be checked >> first is to check if 'num1' is greater than 'num2' and 'num1' is less than or equal to 100 >>> if this condition is true then we want to return 'num1' >> second is to check  if 'num2' is greater than 'num1' and 'num2' is les...

Junior Developer Central JS Practice Exercise - 08

  Question:  Write a Javascript program to concatenate two strings except their first character.  Answer:  function concatStr (str01, str02) { return str01.slice(1) + str02.slice(1); } > we declare a function 'concatStr' > it has two parameters 'str01' & 'str02'  > we simply return the concatenated value of the slice method used on 'str01' & 'str02'  > we need to remove the first character from both the string inputs 'str01' & 'str02'  > so we want the slice to begin from the second character onwards > thus we use 1 as the start parameter as the first character has the position of 0

Junior Developer Central JS Practice Exercise - 07

  Question:  Write a Javascript program to extract the first half of a string of even length.  Answer:  function extHalf (str) { let str001 = str;  if (str001.length % 2 === 0) {  return str001.slice(0, str001.length/2);  } else { return str001 } } > we declare a function 'extHalf' > it has one parameter 'str' > we create a variable 'str001' > we initialize it with a value of our argument 'str'  > we then open if/else statements to check if the length of 'str001' is even > we use the modulo / remainder operator to check if the length is even > if it is even then the modulo operator would have '0' as remainder > if it is odd then the modulo operator would have '1' as remainder > if 'str001' is even then we want to return the first half  > we do that by using the slice method on 'str001'  > our start parameter is 0 as we want to slice the first half > we use str001.length / 2, whic...

Junior Developer Central JS Practice Exercise - 06

  Question:  Write a Javascript program to create a new string from a given string taking the first 3 characters and the last 3 characters of a string 'and adding them together. The string length must be 3 or more, if not, the original string is returned.  Answer:  function stringFormat (str) { let str001 = str;  if (str001.length < 3) { return str001;  } else { let str002 = str001.slice(0, 3);  let str003 = str001.slice(-3);  let finalString = str002+str003;  console.log(finalString); } }  > we declare a function 'stringFormat'  > it has one parameter 'str'  > we create a variable str001 and initialize it with the argument 'str' > we then open an if/else statement to check if the length of the 'str001' is less than 3 > if it is less than 3 then we want the function to return the 'str001' variable  > if it is 3 or more than 3 then we slice the str001 twice  >> our first slice is saved in var...

Junior Developer Central JS Practice Exercise - 05

  Question:  Write a Javascript program to create a new string adding 'New!' in front of a given string. If the given string begins with 'New!' already then return the original string.  Answer:  function newStr (str) { let str001 = str;  if (str001.slice(0,4) === 'New!') { return str001; } else { let str002 = 'New! ' + str001;  console.log(str002);  } } > we declare a function 'newStr' > it has one parameter 'str'  > we declare a variable 'str001' > we initialize it with a value of the argument 'str' > we then use if / else statements to check if the string 'str001' begins with 'New!'  > we use the slice function to check if the string  'str001' begins with 'New!'  > we return the string 'str001' if it does > if the string 'str001' it does not begin with 'New!' then we declare another variable 'str002'  > we initialize the value of t...

Junior Developer Central JS Practice Exercise - 04

  Question:  Write a Javascript program to get the current date Output: mm-dd-yyyy mm/dd/yyyy dd-mm-yyyy dd/mm/yyyy Answer:  function formatDate () { let date = new Date();  let day = date.getDate();  let month = date.getMonth() + 1;  let year = date.getFullYear();  let opt1 = `${month}-${day}-${year}`; let opt2 = `${month}/${day}/${year}`; let opt3 = `${day}-${month}-${year}`; let opt4 = `${day}/${month}/${year}`; console.log(opt1); console.log(opt2); console.log(opt3); console.log(opt4); }; > we declare a function 'formatDate' > it has no parameters > we declare various variables and initialize it with different type of date objects and methods >> 'date' = new Date ();   ===>>> this will return the date object as it is a constructor >> 'day' = date.getDate(); ===>>> this method will return the day of the month >> 'month' = date.getMonth(); ===>>> this method will return the month (0 to 1...

Junior Developer Central JS Practice Exercise - 03

  Question:  Write a Javascript program to replace every character in a given string with the character following it in the alphabet.  Answer:  function replaceChar (str) { str001 = str.toString();  str001 = str001.split('').map(char => String.fromCharCode(char.charCodeAt(0) + 1)).join(''); return str001; } > this function replaces each character of the string with the next character in the alphabet > we first declare a function "replaceChar' > it has one parameter 'str' > we first convert the 'str' parameter to a string using the 'toString() method > we save it in the variable 'str001' > we then use the split method on 'str001' to divide the string in to an array of substrings > after we have split the string 'str001', we use the map method  > the map method will create a new array  > this new array will have the result of calling a function for every array element >> the function ...