Tuesday, July 20, 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 match against a regular expression and returns the matches as an array object
> we want to match the 'str' with the elements in the 'vowels' variable and store the results in the 'result' array
> we declare another variable 'count' and initialize it with a value we get by using the length property on the array 'result' which will give us the total number of elements in the 'result' array
> we return the 'count' variable

Monday, July 19, 2021

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 terminated
> we keep the iterations running till all the elements of the array are checked and terminate the loop by returning 'true'

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
>> condition - we define the condition for the loop to run ('i' must be less than 6)
>> final expression - at the end of each loop iteration we increment the counter variable
>> understanding the statement in the for loop
>> we want to generate a 6 digit hexadecimal color code with a '#' sign before it
>> that 6 digit hexadecimal code needs to be taken from the array we created 'letters' 
>> we use Math.random() to randomly select any of the 16 array elements
>> since array indexes start from 0, we want a random index number from 0 to 15
>> we use the Math.round() method with Math.random() to get a number with no decimals
>> we use both these methods to select a random index number from the 'letters' array
> we then concatenate the result of the 'for loop iteration' with the 'color' string variable
> the for loop will terminate after the 5th iteration and return the 'color' variable

Sunday, July 18, 2021

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
>> so after split ('\n) we get 
>> 0: ["abc, def, ghi"]
>> 1: ["jkl, mno, pqr"]
>> 2: ["stu, vwx, yza"]
> but we need a 2 dimensional array 
> so we need to split each of the values, in the row, into an array itself
>> like this: 
>> 0: ["abc", " def", " ghi"]
>> 1: ["jkl", " mno", " pqr"]
>> 2: ["stu", " vwx", " yza"]
> in order to further split each of the values into an array itself we use the map() method
> the map() method creates a new array with the results of calling a function for every array element
> the map() method calls the provided function once for each element in an array 
> our aim is to further split the row elements we have, into an array itself 
> so we use the map () method and call a function, that will be called on each value of the 'row' 
> so we will use the split () method on each values of the 'row' and split them by the 'comma'
> like this .map(row => row.split(',')
> this will be a one line code and we shall return the same

Thursday, July 15, 2021

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 create a variable 'obj2Keys' 
> we initialize it with a value we get by using the Object.keys() method on 'obj2'
> Object.keys() will return an array of a given object's property names or key names
> so our variable 'obj2Keys' will be an array of key names / property names of 'obj2'
> we then want to return true, if 'obj2Keys' includes all the key names of 'obj1' 
> however we cannot compare 'obj2Keys' to 'obj1' as 'obj2Keys' is an array
> so we use the Object.keys() method on 'obj1' as well 
> this method will return an array
> we also add the every() method on Object.keys(obj1)
> like this: Object.keys(obj1).every()
> the every() method returns true if all elements in an array pass a test
> the every method () executes the function once for each element present in the array
> so within the every () method we want to check if the array 'obj2Keys' includes all the elements in the array that is created [ when we use the '' Object.keys(obj1) '' ]
> so we use the includes() method to compare and check the two arrays
> this test will return 'true' if all elements of the array 'Object.keys(obj1) are included in 'obj2Keys'

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 without a fractional component
> our if statement will check if the value is an integer
> if it is an integer, then we want to return true
> if it is not an integer, then we want to return false
> we return false as the value stored is not a whole number and so the value stored in 'leapYear02' is not divisible by 4
> if it is not divisible by 4 then it is not a 'leap year'