Posts

Showing posts from June, 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...

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

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' 

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...

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...

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: ‘ [] ‘ >...

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...

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 th...

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...

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' whi...

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...

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 > ...