Skip to content

Instantly share code, notes, and snippets.

@dbsimeonov
Last active January 17, 2018 15:45
Show Gist options
  • Save dbsimeonov/b729cb72b38a729da9938e6a96989a85 to your computer and use it in GitHub Desktop.
Save dbsimeonov/b729cb72b38a729da9938e6a96989a85 to your computer and use it in GitHub Desktop.
Here I will post the solutions for the challenges from Free Code Camp. I will try to explain all of them with comments and steps for solving the task. Most of them will try to use different approaches/methods for solving them. Please if you feel there is a better way, share it with us!

Chunky Monkey

For loop + push().slice()

  • Creating an empty array
  • For loop which on each irretation will add the value of size
  • push the content from i to i + size into the result array
function chunkArrayInGroups(arr, size) {
  var result =[];
  
  for(var i = 0; i < arr.length; i+=size){
    result.push(arr.slice(i, i + size));
  }
  return result;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

While loop + push().slice()

function chunkArrayInGroups(arr, size) {
  var result =[];
  i = 0;
  while(i < arr.length){
    result.push(arr.slice(i, i + size));
    i+=size;
  }
  return result;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

While loop ** splice()

  • The while loop will loop till the arr.length till its not 0
function chunkArrayInGroups(arr, size) {
  var newArr = [];
  while (arr.length) {
    newArr.push(arr.splice(0,size));
  }
  return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

str.substring()

function confirmEnding(str, target) {

  return str.substring(str.length - target.length)===target ?true: false;
}

confirmEnding("Bastian", "r");

for loop + substr

  • Very comfortable way with for loop
  • Simply targeting only str.length and looping till it matches target

function confirmEnding(str, target) {
for(var i=0;i < str.length; i++){
    if(str.substr(i-str.length) === target){
      return true;
      
    }
  }return false;
}

confirmEnding("Basdadatian", "rad");

Mutations

This challenge was though.

Solution 1

  • Making sure that both arrays are lowerCase because indexOf is case sensitive
  • Creating a for loop that is checking that target has the indexes inside test[i]
  • If any of them is false == -1 to return false
function mutation(arr) {
  var test = arr[1].toLowerCase();
  var target = arr[0].toLowerCase();
  for(var i =0; i< test.length; i++){
    if(target.indexOf(test[i]) == -1)
      return false;
  }return true;
}
mutation(["hello", "hey"]);

Solution 2

function mutation(arr) {
  var check=0;
  for(i=0;i<arr[1].length;i++){
    check=arr[0].toLowerCase().indexOf(arr[1][i].toLowerCase());
    
    if(check==-1){
    return false;
    }
  }
  return true;
}

Repeat a string repeat a string

Beginners way with .push(), .join(); and for loop

  • Creating a for loop to irretate till num value
  • Each time the loop activates will push the content of str
  • After the for loop will join the result
function repeatStringNumTimes(str, num) {
 var array= [];
  
  for(var i =0; i< num; i++){
   array.push(str);
  }
  return array.join("");
}

repeatStringNumTimes("abc", 3);

if statement with .repeat();

function repeatStringNumTimes(str, num) {
 if(num>0){
    return str.repeat(num);
  }
  return "";
}

stolen* nested function

function repeatStringNumTimes(str, num) {
  if(num < 0)
    return "";
  if(num === 1)
    return str;
  else
    return str + repeatStringNumTimes(str, num - 1);
}

stolen* ternary?true:false; +repeat

function repeatStringNumTimes(str, num) {
  return num > 0 ? str.repeat(num) : '';
}

repeatStringNumTimes("abc", 3);

Return Largest Numbers in Arrays

solving it with 2 for loops

Instructions how to build the function

  • Create 2 variables, one of them would be number set to 0 and an empty array stored as result
  • Jump on the first loop which will give as the arrays intro arr and we will store it as variable array
  • We will go deeper with another for loop which will loop thru the content of the selected array and store each number in variable called arrN
  • Create a if statement where you are checking which number will be highest and store the highest one in number that we created earlier
  • After the second for loop we will use .push() to put the highest number into the array we created result and we will reset the number back to 0 for the next irritation of the loop
  • After the first for loop just return the final result array
function largestOfFour(arr) {
  var number = 0;
  var result = [];
  
  for(var i = 0; i < arr.length; i ++){
    var array = arr[i];
    
    for(var n = 0; n < arr[i].length; n++){
      var arrN = array[n];
      if (number < arrN){
        number = arrN;
      }
    }
    result.push(number);
    number = 0;
  }
  
    return result;
   
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

solved it with mixture of ES6 & ES5

function largestOfFour(arr) {
  var result = []

  for(let subArray of arr) {
    let highest = subArray[0]

    for(let number of subArray) highest = highest > number ? highest : number

    result.push(highest)
  }

  return result
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);


shorter version with loops

function largestOfFour(arr) {
  var result = []
  for(let subIndex in arr) {
    for (let number of arr[subIndex]) result[subIndex] = result[subIndex] > number ? result[subIndex] : number
  }
  return result
}

the same thing just with 2 functions and more readable

function highestInArray (numbers) {
  let highest = numbers[0]

  for(let number of numbers)
    highest = highest >= number
              ? highest
              : number

  return highest            
}

function largestOfFour(arr) {
  var result = []

  for(let subArray of arr)
    result.push(highestInArray(subArray))

  return result
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

.map(); Still trying to learn more about the map function

  • Here we create a variable which is mapping the content of arr with x
  • Creating variable max = 0 which will be our result for the highest number
  • For loop into X which is checking each number and storing the highest in max variable
function largestOfFour(arr) {
  var arrNew = arr.map(function(x){
    var max = 0;
    for (var i = 0; i < x.length; i++){
      if (x[i] > max){
        max = x[i];
      }
    }
    return max;
  });
  return arrNew;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Math.max + .apply

function largestOfFour(arr) {
  var maxArr=[];
  for(i=0;i<arr.length;i++)
    {
      maxArr.push(Math.max.apply(null ,arr[i]));
    }
  return maxArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Slasher Flick

Easy challenge with many ways of solving it with 1line of code

N1 * splice()

function slasher(arr, howMany) {
  arr.splice(0, howMany);
  return arr;
}
slasher([1, 2, 3], 2);

N2 * slice()

function slasher(arr, howMany) {
  return arr.slice(howMany);
}

N3 * functional programming with .filter

function slasher(arr, howMany) {
  return  arr.filter(function(item,index){
    return index > howMany-1; 
  });
}

Approach with for loop

function capitalize (aString) {
  return aString[0].toUpperCase() + aString.toLowerCase().slice(1);
}
function titleCase(str) {
  var splitStr = str.split(" ");
  for(var i = 0; i < splitStr.length; i++){
    splitStr[i] = capitalize(splitStr[i]);
  }
  return splitStr.join(" ");
}
titleCase("I'm a little tea pot");
  • First we create a function called capitalize that is selecting the first character of aString and applies toUpperCase(). After that we transform the rest of the string into toLowerCase and slicing the upperCase character
  • Creating a variable called splitStr to create an array using split()
  • Creating a for loop that follows each array and applies the capitalize function
  • Don't forget to use join for returning the original string with no arrays

Approach with .map()

function capitalize(aString){
  return aString[0].toUpperCase() + aString.toLowerCase().slice(1);
}
function titleCase(str) {
  var array = str.split(" ");
  var result = array.map(capitalize);   
  return result.join(" ");
}
titleCase("I'm a little tea pot");
  • This one uses the capitalize function as the previous one
  • Instead of for loop to select the different arrays, we are using array.map

Truncate a string

It took me a while till I understand the task, and tip from me - check the test cases, they will help you to understand and roughly idea how the function will work.

*This one is easy task, try to do it completely alone. If you find different approach, feel free to share it.

Beginners way with .slice() + .concat()

function truncateString(str, num) {
  if(num > 3 && num < str.length){
    return str.slice(0, num - 3).concat('...');
  }else if(num < 3){
    return str.slice(0, num).concat("...");
  }else{
    return str;
  }
}
truncateString("A-tisket a-tasket A green and yellow basket", 11);

Same things with ternary operator

function truncateString(str, num) {
  if (str.length > num)
    return str.slice(0, num > 3 ? num-3 : num).concat("...");
  return str;
}
truncateString("A-tisket a-tasket A green and yellow basket", 33);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment