Tuesday, June 29, 2021

Junior Developer Central JS Practice Exercise - 02

 
Question: 

Write a Javascript program to get the extension of a filename. 





Answer: 

function fileNameExt (str) {

let extFileName = str.slice(str.lastIndexOf('.'));

return extFileName;

}




> declare a function 'fileNameExt' 
> it has one parameter 'str' 
> we declare a variable 'extFileName' 
> it is initialized with a value when we use some basic string methods to get our output
> our program should extract the extension of a filename and return just that
>> like this: fileNameExt ('index.html') should return '.html'
> so first we use the slice function to slice the input and return the last portion of the string 
> in order for the slice function to work, we need to pass in a start index number and an end index number (optional)
> since we do not know what the filename is, we cannot be sure of a specific index number
> the one thing we are sure of is that the extension name of a file is always followed by a dot
> however we do not know as to what type of file it is as it can have two dots as well 
>> like this: webpack.config.js
> in the above example we have a file name that has two dots
> so we use the lastIndexOf method to find the last occurence of the dot in the filename
> we enter the lastIndexOf - 'dot' as the start number we want to pass, in the slice method
> this will slice our input string and return the entire portion following the last dot in a filename
> we then return the variable 'extFileName'

Junior Developer Central JS Practice Exercise - 01


Question:

Write a Javascript program to check two numbers and return true if one of the number is 100 or if the sum of the two numbers is 100.





Answer:

function check2nos (a,b) {

if (a === 100 || b === 100 || (a+b) === 100) {

return true;

} else { 

return false

}

};





> declare a function check2nos
> it has two parameters 'a' and 'b'
> we use an 'if / else statement' to check our conditions before we return the answer
> we have three major conditions to fulfil
>> we have to check if 'a' equals 100 or
>> we have to check if 'b' equals 100 or
>> we have to check if 'a + b' equals 100
> if any one of the above three conditions are met, then our program must return 'true
> else it should return false

Tuesday, June 15, 2021

Javascript Practice 80: JS Hero - To be continued ...

 
Question: 

Write a function digitsum that calculates the digit sum of an integer. The digit sum of an integer is the sum of all its digits.

Example: digitsum(192) should return 12.




Answer: 

function digitsum (n) {

let digits = n.toString().split('').map(x => x * 1); 
let sum = digits.reduce((acc,cv) => acc + cv); 
return sum;
};




> declare a function 'digitsum'
> it has one parameter 'n' 
> we create our first variable 'digits' 
> we initialize it with the output we get by converting the input 'n' 
>>> from a number to a string, 
>>> then splitting the string in an array format 
>>> and then converting the array of strings to a number by using the map method
> we then create our final variable sum and initialize it with a value we get by using the reduce method on the variable 'digits' 
> finally we return 'sum' 

Monday, June 14, 2021

Javascript Practice 79: JS Hero - Project Euler

 
Question: 

Write a function sumMultiples taking a natural number n and returning the sum of all multiples of 3 and of 5 that are truly less than n.

Example: All multiples of 3 and 5 less than 20 are 3, 5, 6, 9, 10, 12, 15 and 18. Their sum is 78. sumMultiples(20) should return 78.





Answer: 

function sumMultiples (n) {

let sum = 0; 

for (let i = 1; i < n; i++) {
if (i % 3 === 0 || i % 5 === 0) {sum += i;}
}

return sum; 

};




> we declare a function 'sumMultiples'
> it has one parameter 'n' 
> we declare a variable 'sum'
> we initialize it with a value of '0' 
> we open a 'for loop' 
> this loop will use all the numbers below 'n' to check for our conditions
> we open an 'if' statement that will have to meet any one of the two conditions to execute the code in its block
> the 'for loop' will only add the number to the 'sum' if it is a multiple of 3 or 5 
> it will not add any number to the sum if there are no multiples of 3 and 5
> once the for loop has met its terminating condition then we simply return the 'sum' 

Sunday, June 13, 2021

Javascript Practice 78: JS Hero - Roman numerals II

 
Question: 

Write a function roman that converts an Arabic number (up to 1000) into a Roman numeral.

Example: roman(483) should return 'CDLXXXIII'.




Answer: 

function roman (n) {

let romanObj = {

M: 1000, 
CM: 900, 
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1

};

let roman2 = ''; 

for (let key in romanObj) {

while (n >= romanObj[key]) {

roman2 += key;
n -= romanObj[key]; 

}
}
return roman2; 
}; 





> we declare a function 'roman'
> it has one parameter 'n'
> we declare a variable ‘romanObj’ 
> we initialize it with roman numerals and their values in ‘key: value’ format
> like this: {I:1, V:5, X:10, etc}
> thus we make the variable ‘romanObj’ an object; that holds multiple values in terms of properties and methods
> we declare another variable ‘roman2’ and it is an empty string
> we leave it empty as we shall initialize it later by adding the roman version of the integers and then return it later
> we first use the ‘for in loop’ to loop through every key value pair of the ‘romanObj’ object
> to access the key; we can log the key or console.log(‘key: ‘, key) / console.log(key)
> to access the value; we can log the value or console.log(‘value: ‘, romanObj[key]) / console.log(romanObj[key])
> inside this ‘for in loop’ we run another ‘while loop’ 
> so while our number ‘n’ is greater than or equal to the value or romanObj[key], then in that case we want to add the value to roman2; our value will be the key
> like this: roman2 += key
> every time a key is added to the ‘roman2’ variable we also need to subtract that key value from our number ‘n’
> like this: n -= romanObj[key]
> so the while loop iteration keeps looping till our number ‘n’ is less than romanObj[key] or the key value
> the while loop stops when ‘n’ is less than romanObj[key] or the key value
> after that the outer ‘for in loop’ stops 
> and then we can return roman2

Javascript Practice 77: JS Hero - Roman numerals I

 
Question: 

Write a function arabic that converts a Roman number (up to 1000) into an Arabic.

Example: arabic('CDLXXXIII') should return 483.





Answer: 

function arabic (s) {

let romanObj = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; 
let arabicArr = []; 

for (let i = 0; i < s.length; i++) {

if (romanObj[s[i]] < romanObj[s[i+1]]) {

arabicArr.push(romanObj[s[i+1]] - romanObj[s[i]]); 
i++; 
continue;
} else {arabicArr.push(romanObj[s[i]]);}

}
return arabicArr.reduce((acc,cv) => acc + cv);
}




> we declare a function ‘arabic’
> it has one parameter ‘s’ 
> we declare another variable ‘romanObj’ 
> we initialize it with roman numerals and their values in ‘key: value’ format
> like this: {I:1, V:5, X:10, etc}
> thus we make the variable ‘romanObj’ an object; that holds multiple values in terms of properties and methods
> we also declare another variable ‘arabicArr’ , it is an empty array, like this: ‘ [] ‘
> we leave it empty; it will be used to push the value we get while processing the code in the function ‘arabic’
> we open a ‘for loop’ to process the function ‘arabic’, where we want to convert the roman numerals into integers or ‘arabic’
> the ‘for loop’ will go through the string ‘ s ‘, one element at a time; like this: ‘III’ – [ ‘I’, ‘I’, ‘I’ ] 
> inside the ‘for loop’ we test if our first roman numeral is less than the second roman numeral, for eg: ‘IV’
> where I = 1 && V = 5
> so we want to take the string ‘s’ value at that index and compare it to the values provided in the ‘romanObj’ variable
> if the strings ‘s’ value at the index is greater than the consecutive index value then we want to subtract it from the consecutive index value
> like this: 5 – 1 = 4; 
> we then want to push it to the array ‘arabicArr’ variable
> we then push the iteration up by i++ and then we break out of the iteration of the for loop by using ‘continue’
> if it is not greater than we want it to be pushed inside the ‘arabicArr’ variable
> once the for loop has gone through all the values then we want to return the ‘arabicArr’ array
> since we want the result to be returned in integers, we want the sum of all values of the array ‘arabicArr’ 
> so we use the reduce function, with the accumulator adding all the current values of the ‘arabicArr’  array
 




Friday, June 11, 2021

Javascript Practice 76: JS Hero - Recursion

 
Question: 

Write a function reverse that reverses the order of the characters in a string. The function should be recursive.

Example: reverse('live') should return 'evil'.




Answer: 

function reverse (str) {

if (str < 1) {

return ''; 

} else {

return reverse(str.substr(1)) + str.charAt(0);

}
};





> we first declare a function 'reverse'
> it has one parameter 'str' 
> our goal is to take a string and reverse it as the name suggests
> we shall do the reversing using recursion 
> recursion is a function or a method that calls itself several times till it meets the base case 
> because it is a recursion we shall be needing a base case
> this base case will let us know when to stop running the recursion over and over 
> in the process of 'reverse' function we shall be chopping off the first letter / character over and over
> which will eventually lead to the length of the string be: ' less than 1 ' 
> so when our string length is ' less than 1 ' our string is empty and we want to return it
> and so we return an empty string: '' ; as we want the end result to be a 'string'
> we do that like this: if (str < 1) return ''
> now we start to think about the else statement 
> we want our string to be in reverse 
> so we want to return each of the letters / characters in reverse order
> so the first thing we need to do is to get the first character of our string
> we shall use the charAt(0) method to get our first character / letter
> after we get the first letter / character of the string then we want to run the 'reverse' function on all the letters / characters after the first letter / character
> so if our string was: 'hello' 
> then by using charAt(0) we would get the letter / character 'h' 
> we then would want to use the 'reverse' function on 'ello'  and simultaneously append all the first characters
> and consequently get rid of one letter each time 
> so the way to get rid of the first letter and still run the function is to use the substr() method
> like this: reverse(str.substr(1)) + str.charAt(0) 
> this will keep repeating itself till our base case is met which is an empty string
> for eg. if our string is: 'hello'  we would want 'olleh'
> step 01 = ello + h
> step 02 = llo + e + h 
> step 03 = lo + l + e + h
> step 04 = o + l + l + e + h
> thus when the 'if' condition is true then we shall be returned with a reversed string







Javascript Practice 75: JS Hero - Functions call functions

 
Question: 

Write a function sum that takes an array of numbers and returns the sum of these numbers. Write a function mean that takes an array of numbers and returns the average of these numbers. The mean function should use the sum function.




Answer: 

function sum (arr) {

let totalSum = arr.reduce((acc,cv) => acc + cv);

return  totalSum; 

}; 

function mean (arr) {

let meanVal = sum(arr) / arr.length;

return meanVal;

}; 




> we declare a function 'sum'
> it has one parameter 'arr' 
> we declare a variable 'totalSum' 
> we use the reduce method to reduce the value in the array to 1 unit
> we also want to add each and every element of the array
> we use the accumulator and the current value to do that 
> it works like a snow ball, keeps accumulating the values from left to right in an array
> this accumulated amount gets stored in the 'totalSum' variable
> we then return the 'totalSum' variable at the end of the 'sum' function 
> we then declare another function 'mean' 
> it has one parameter 'arr' 
> we declare a variable 'meanVal' 
> we want to store the mean value / average of the numbers in an array in the 'meanVal' variable
> to get the average of the numbers, we need to add the numbers and divide it with the total numbers
> like this: 2 + 4 + 6 + 8 = 20; 20 / 4 = 5;
> in order to get the sum of all the elements in an array, we can use the function 'sum' that we created in this function 'mean' 
> like this: sum(arr)
> we then need to divide this number with the total number of elements in the array
> like this: sum(arr) / arr.length
> we store the result in the variable 'meanVal' 
> we return the variable 'meanVal' to get our answer

Javascript Practice 74: JS Hero - String: split()

 
Question: 

Write a function add that takes a string with a summation task and returns its result as a number. A finite number of natural numbers should be added. The summation task is a string of the form '1+19+...+281'.

Example: add('7+12+100') should return 119.




Answer: 

function add (str) {

const red = (acc, cv) => acc + cv; 
let abcd = str; 
let cdef = abcd.split('+').map(Number); 

return cdef.reduce(red); 





> we declare a function 'add'
> it has 1 parameter 'str' 
> we first declare a variable to use in the reduce method and call it 'red' 
> it basically stores the accumulated value of the array elements which are numbers 
> we then declare a variable 'abcd' which will be the string
> we then convert that string into an array object and use the map method to convert it to a number
> we store that output in a variable 'cdef' 
> we then reduce the 'cdef' variable to a single number by using the reduce method  
> we use the function 'red' along with reduce method
> we return that statement to get our answer

Javascript Practice 73: JS Hero - NaN

 
Question: 

Write a function parseFirstInt that takes a string and returns the first integer present in the string. If the string does not contain an integer, you should get NaN.

Example: parseFirstInt('No. 10') should return 10 and parseFirstInt('Babylon') should return NaN.





Answer: 

function parseFirstInt (input) {

  let inputToParse = input;

  
for (let i = 0; i < input.length; i++) {
   
 let firstInt = parseInt(inputToParse);
   
 if (!Number.isNaN(firstInt)) {
      
     return firstInt;

}

     inputToParse = inputToParse.substr(1);

}

return NaN;
};






> we declare a function 'parseFirstInt' 
> it has 1 parameter 'input' 
> we declare a variable 'inputToParse' 
> we initialize it with a value of the input string
> we use a 'for loop' to loop over the elements of the input string
> we then declare another variable inside the 'for loop' which is 'firstInt'
> we initialize its value with the output we get when we run the parseInt method on variable 'inputToParse'  and store them in the firstInt variable
> for eg lets say our 'inputToParse' is 'Javascript 101'
> so parseInt will give us a NaN output
> this will be stored in firstInt variable
> we then open an ' if ' statement to check if firstInt is ' NaN ' or ' not NaN '
> if it is NaN then the code inside the block of ' if ' statement does not run
> instead we apply the substr(1) method which returns a portion of the string from the index 1 and extending up to the last index.
> so the new 'inputToParse' value shall be ' avascript 101'
> this value will get stored in the 'firstInt' variable and again the condition in the ' if ' statement will be checked 
> this process will keep on repeating itself till the loop stopping condition is met
> if we encounter any numbers then they get stored in the 'firstInt' variable
> if there are no occurrences of numbers then we will have nothing stored in the variable 'firstInt' 
> the stopping condition is met once we run out of characters in 'inputToParse' variable
> so if we do have numbers then the function will return the integer
> if the stopping condition is met and we do not find any integers then we shall be returned NaN

Friday, June 4, 2021

Javascript Practice 72: JS Hero - The arguments object

 
Question: 

Write a function max that calculates the maximum of an arbitrary number of numbers.

Example: max(1, 2) should return 2 and max(2, 3, 1) should return 3.




Answer: 

function max () {

let acb = [...arguments]; 

acb.sort((a, b) => b - a);

return acb[0];

}





> we declare a function max
> it has no parameters
> we declare a variable 'acb'
> we initialize it with a value using the spread operator
> spread operator converts our arguments / numbers which are strings to arrays
> we then use the sort method, on our array 'acb' created by the spread operator, 
> we use the sort method to arrange the numbers in our array in descending order
> like this: acb.sort((a,b) => b - a )
> if we wanted to arrange the numbers in our array in ascending order we can do the opposite
> like this: acb.sort((a,b) => a - b )
> so basically we convert the string in to array and then sort the array in descending order
> now in order to get the maximum number we simply return the first element of our array
> like this: return acb[0]
> we shall get our maximum number

Javascript Practice 71: JS Hero - Nested loops

 
Question: 

Write a function sum that calculates the sum of all elements of a two-dimensional array.

Example: sum([[1, 2], [3]]) should return 6.




Answer: 

function sum (arr) {

let arr2 = arr.flat(); 

return arr2.reduce((a, b) => a + b, 0);

}




> we declare a function sum
> it has 1 parameter 'arr'
> first we create a variable arr2
> we initialize it with the output we get by using the flat() method on 'arr' parameter
> the flat() method flattens an array with an option of 'depth' 
> you can pass in any levels of nesting with the flat () method
> once our array has been flattened, we then return our array with the reduce method
> the reduce method reduces the array elements to a single value
> we use the reduce method to find the sum of all numbers in our array

Javascript Practice 70: JS Hero - break and continue

 
Question: 

Write a function isPrime that checks whether a passed number is prime. In case of a prime number it should return true, otherwise false.

Example: isPrime(7) should return true and isPrime(8) should return false.




Answer: 

function isPrime (n) {

if (n <= 1) return false; 

for (let i = 2; i < n; i++) 

if (n % i == 0) return true; 

return false; 

};





> a prime number is a natural number
> it is greater than 1
> it is only divisible by 1 and itself; eg 7 
> so  (7 % 1 = 0) & (7 % 7 = 0)
> but 7 % any other number is not 0; meaning it will always have a remainder
> this is because 7 is not divisible by any other number
> 1 is not a prime number 
> to be a prime number; the condition is to be divisible by any 2 positive divisors
> 7 is divisible by 7 & 1; 
> 3 is divisible by 3 & 1
> since 1 is only divisible by 1 and no other number, it does not fulfil the condition
> ∴ 1 is not a prime number
> we start by declaring a function isPrime
> it has 1 parameter ' n '
> we open an 'if' statement to check if the number 'n' provided is less than or equal to 1
> like this n <= 1
> it is supposed to check if the number is less than 1; prime nos are greater than 1
> it is also supposed to check if the number is equal to 1; 1 is not a prime number
> if the condition is true; then our function will return false and terminate the function
>> if it is not true then we proceed further down towards another check in the form of a loop
>> we open a 'for' statement
>> a 'for' statement creates a loop 
>> this loop consists of 3 optional expressions followed by a block statement
>> block statement is executed in the 'for' loop 
>> 3 optional expressions are - initialization, condition & final expression
>>> initialization: we declare a variable only once before the loop begins
>>>> we initialize the 'for' loop with the number 2
>>>> this is because we already checked if the number is 1 or less than 1
>>>> it has gone past that condition to check the number
>>>> if the number is not 1 or less than 1, then it has to be more than 1
>>>> which is why we start the loop with number 2
>>> condition: this condition is evaluated before each loop iteration
>>>> if the condition is true then block statement is executed
>>>> if the condition is false then for loop is exited without execution to the next line of code
>>>> our number (n) has to be between 2 & n
>>>> we express our condition like this: i < n; we know that i = 2 already
>>> final expression: this is evaluated at the end of each loop iteration
>>>> executed every time after the code block has been executed
>>>> it increases / decreases the value each time the code block has been executed
>>>> like this i++ / i--
>>>> this final expression will keep increasing or decreasing and is based on the condition
>>>> if the condition is met then it will stop incrementing or decrementing
>>>> it only works till the condition is not met
>>>> our condition is i < n
> for eg '' for (let i = 2; i < 5; i++)
> our loop will start at 2
> it will check if 2 is less than 5
> it will execute the code in the block below it
> it will then increase the variable 'i' by 1
> it will again check if i + 1 < 5 and if it is, then it will execute the code in the block below again
> after the execution of the code in the block below, it will again increment the value of i by 1
> this will keep happening as long as i < 5
> this is why it is called as a 'loop' 
> once i = 5, the loop will stop and proceed to the next code below the for loop
>>> after the construction of the for loop and its three expressions we open a statement
>>>> this statement is to be executed as long as the condition in the loop is true
>>>> we open an 'if' statement
>>>> our condition is to check if the 'n' divided by i, has a remainder of 0
>>>> like this: (n % 1 == 0)
>>>> if it does have a remainder of 0, then our condition is true
>>>> if our condition is evaluated as true then we return false and stop the execution
>>>> if our condition is evaluated as false then it re-iterates back with an incremented number
>>>> this keeps on happening till 'i = n'
>>>> the loop will then stop functioning and return 'true'

or

> to check if a number is prime, first we need to check if it is not 1
> after we have checked that, then we need to check if this number is divisible by any other number except 1 and itself; i.e. 2 divisors
> if it is divisible by any other number apart from the 2 divisors then it is not a prime number
> our code should reflect the above 2 points
> we check if the number is 1; if its not then we proceed with other code
> to check the number of divisors a particular 'number n' has, we simply divide it by all the numbers below it and check the remainder of that division
> we do that by creating a for loop with an 'if' condition
> this loop will divide the number by all the numbers below it and check the remainder 
> if the remainder is 0 then our number is not prime
> if the remainder is not 0, then our loop will keep executing till it stops