Discussion, Questions, and Resources for Part 2 (JavaScript Basic Algorithms, Object-Oriented, and Functional Programming - April 2018 Cohort)

Repeat a string
function repeatStringNumTimes(str, num) {
  // repeat after me
 let array1 = "";
 if (num <= 0) {
   return "";
 }
 for (let i = 0; i < num; i++) {
   array1 = array1 + str.slice();
 }
 return array1;
}

repeatStringNumTimes("abc", 3);
Truncate a string

function truncateString(str, num) {
  // Clear out that junk in your trunk
	let newArray = '';
	let dots = '...';
	if (str.length > num) {
		newArray = str.slice(0, num).concat(dots);
	}
	if (str.length <= num) {
    newArray = str;
  }
  return newArray;

}

truncateString("A-tisket a-tasket A green and yellow basket", 8);
Finders keepers
function findElement(arr, func) {
  let num = 0;
  for (let i = 0; i < arr.length; i++) {
    if (func(arr[i]) === true) {
      return num = arr[i];
    }
  }
}

findElement([1, 2, 3, 4], num => num % 2 === 0);
BooWho
function booWho(bool) {
  // What is the new fad diet for ghost developers? The Boolean.
  if (bool === true || bool === false) {
    return true;
  } else { return false;}
  
}

booWho(null);

Honestly I was so happy to get them that I didnā€™t look much into the final solutions. Glad you guys posted them up! Iā€™ve reached #100daysofcode so I took the weekend off, lol.

1 Like

@nvrqt03 and @alhazen1 thanks for sharing your code! Anyone else come up with different code or have questions/comments about whatā€™s been shared so far?

Here are the next three algorithms I completed:

Boo who

My first attempt was to check if the passed in parameter equals either true or false. If it does, return true, otherwise return false:

function booWho(bool) {
  return bool === true || bool === false;
}

In the Boo Who fCC Guide in hint 2, it suggests using the typeof operator, so I came up with this, which is identical to the solution in the guide:

function booWho(bool) {
  return typeof bool === 'boolean';
}
Title Case a Sentence

For my first attempt, I used split(), map(), toUpperCase(), slice(), toLowerCase(), and join():

function titleCase(str) {
  /* 
   1. str.split(' ') - Split the sentence into individual words to create an array.
   
   2. .map(word => word[0].toUpperCase() - Take the first letter of each word and make it uppercase.
  
   3. word.slice(1).toLowerCase() - Take the remaning letters of the word and make them lower case.
   
   4. word[0].toUpperCase() + word.slice(1).toLowerCase() - Join the first letter with the remaining letters of the word.
   
   5. .join(' ') - Join each word, separated by a space, into one string.
   */
  
  return str.toLowerCase().split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ');
}

After thinking about this more and looking at some more built-in JavaScript methods, I came up with a way to do this using substr():

function titleCase(str) {
  return str.toLowerCase().split(' ').map(word => word[0].toUpperCase() + word.substr(1)).join(' ');
}

Both solutions are relatively similar. The Title Case a Sentence fCC Guide has some other ways to do this that seem more complicated and verbose to me, but maybe they make more sense to others. I do like the regex (i.e. replace()) solution:

function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}

The regex here creates a capture group (^|\s) which looks for either the beginning of the string or a space/tab/line break thatā€™s next to a character thatā€™s not a space/tab/line-break (\S), then returns all matches /g in the string.

Falsy Bouncer

I was able to refactor my first attempts into the following which uses filter():

function bouncer(arr) {
  return arr.filter(item => item);
}

According to the Falsy Bouncer fCC Guide, itā€™s possible to use the Boolean function within filter() like this:

function bouncer(arr) {
  return arr.filter(Boolean);
}

This is a good reminder that built-in functions can be used within map(), reduce(), and filter() functions, not just functions created at the moment (i.e. anonymous functions).

Thanks everyone for looking over my and otherā€™s code and sharing your own code. Iā€™ve learned a lot from you all so far and Iā€™m really grateful for this forum and the fCC community in general. :sunny:

2 Likes

Good stuff to know. I had never thought about that.

Here are the last three algorithms for this section:

Where Do I Belong

I way overcomplicated this one. My solution involved if/else conditions:

function getIndexToIns(arr, num) {
  let sortedArr = arr.sort((a, b) => a - b);

  if (arr.length === 0) {
      return 0;
  }
  
  else {
  
    for (let item of sortedArr) {
      let itemIndex = sortedArr.indexOf(item);

      if (item >= num) {
        return itemIndex;
      }
      else if (sortedArr[itemIndex + 1] === undefined) {
        return itemIndex + 1;
      }
    }
  }
}

There are a few different ways to solve this challenge. The two I like the best, from the Where Do I Belong fCC Guide are:

function getIndexToIns(arr, num) {
  arr.push(num);
  arr.sort(function(a, b){return a-b});
  return arr.indexOf(num);
}

Of course! Add the number into the array, sort, and then return the position of the number. So simple, yet I didnā€™t think to do it this way. The following is basically the same, but on one line:

function getIndexToIns(arr, num) {
  return arr.concat(num).sort((a,b) => a-b).indexOf(num);
}
Mutations

I was able to get this down to the following:

function mutation(arr) {
  let word1 = arr[0].toLowerCase();
  let word2Arr = arr[1].toLowerCase().split('');

  return word2Arr.filter(letter => word1.indexOf(letter) === -1).length === 0;
}

This creates a new array of only the letters that arenā€™t in both words, then returns true if all letters are in both words (i.e. if the length of the new array is zero) and false if not.

Chunky Monkey

I was able to get this:

function chunkArrayInGroups(arr, size) {
  let newArr = [];
  while (arr.length !== 0) {
    newArr.push(arr.splice(0, size));
  }
  return newArr;
}

This solution creates an empty array. Then, runs a while loop until the length of the passed-in array is zero. Each time it runs through the loop, itā€™ll push a splice of the array between zero and size to the new array. Since splice removes the items from the passed-in array, the next pass through the loop will start with the spliced array with the previous items already removed.

I tried to do this recursively, but couldnā€™t figure it out. Can anyone share a solution of this challenge being solved recursively?

Thatā€™s it for me and the Basic Algorithm Scripting section of the beta curriculum. Whereā€™s everyone else at the halfway mark for this part of the cohort? :sunny:

2 Likes

Hereā€™s my final Mutations

function mutation(arr){
  var source = arr[1].toLowerCase().split('');
  var target = arr[0].toLowerCase();
  
  return source.every(function(el){
    return target.includes(el);
  });
}

This is what I started off with

function mutation(arr) {
  let sample = arr[1].toLowerCase();
   let test = arr[0].toLowerCase();
   for(let char of sample){  // test every case for failure (no match)
    if(test.indexOf(char) === -1){
       return false;
     }
   }
   return true;  //if no cases fail 
 }
2 Likes

Thank you for sharing your solutions! :smiley:

Iā€™m on Object Oriented Programming and Intermediate Algorithm Scripting.

where do I belong

little different than yours @camper - my thought was just to push the num to the array, and then sort. ran into the issue where it sorts based on the first number, but found the sorting function. after that it was just returning the index of num.

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
   arr.push(num);
   let arr2 = arr.sort(function(a, b) {return a-b;});
  //console.log(arr);
return arr2.indexOf(num);


}

getIndexToIns([40, 60], 50);
Mutations
function mutation(arr) {
   var firstWord = arr[0].toLowerCase();
  var secondWord = arr[1].toLowerCase();
  
  for (var i = 0; i < secondWord.length; i++) {
   if (firstWord.indexOf(secondWord[i]) === -1) 
     return false;
   }
  return true;

}
chunky monkey

I originally used slice(), but would run into an infinite loop because the loop is still running. was trying to figure out a way to stop the loop, but used splice because it changes the array.


function chunkArrayInGroups(arr, size) {
  // Break it up.
   let chunks = [];
  while (arr.length > 0) {
    chunks.push(arr.splice(0, size));
   
  }
  return chunks;

}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

On to Object Oriented Programming! Iā€™m glad the algos at least made sense. the first time through on the legacy side I was completely lost for most of it and it took me a long time to get through them. at least this time I generally know what I want the code to do, its just figuring out if thereā€™s a method to make my life easier.

3 Likes

While going through the Object Oriented Programming section, I felt like I needed some more information about JavaScript objects. @QuincyLarson recently shared (in his email newsletter) Cynthia Leeā€™s Medium article about JavaScript objects. I found it to be comprehensive and helpful. I plan to refer back to it often:

I like that it starts from the beginning and includes the ES6 class keyword at the end. :sunny:

3 Likes

Thanks @camper! I needed it :slight_smile:

Anyone else having issues accessing the beta site? looks like mine is down.

Mine as well!
It goes to maintenance pageā€¦

Same here, maintenance page as well.

Itā€™s working now with new UI :smiley:

And itā€™s unable to log in yetā€¦

@NariRoh, @lieberscott, @nvrqt03, and others,

The challenges can be found here: https://learn.freecodecamp.org.

Thereā€™s no login capability at the moment, but at least youā€™ll be able to work on and finish the challenges while we wait for the dust to settle.

I updated the links in the first post to reflect the new Learn site:

1 Like

i clicked explore lesson map and it did nothing

A modal should have popped up.

Maybe you have a popup blocker? Just a guess.

I can explore the curriculum, except the ā€œQuality Assurance and Testing With Chaiā€ curriculum isnā€™t working for me. Anyone else?

Iā€™m seeing the same thing @lieberscott.
This also does not seem to be tracking progress at all, so need to remember where we left off I guess. Thatā€™s a bit frustrating.

Iā€™m able to access the lessons now, but youā€™re right - the login doesnā€™t work, and its not tracking progress. We can still access the lessons, but its much better if our progress can be tracked. these lessons and challenges would be great to review before interviews, etc - especially any of the algorithmic challenges.

Object oriented programming module complete, will start the functional programming section soon. On track to finish by 5/31 deadline. I wish the beta version up so we can keep track/get credit, but Iā€™m taking a lot of notes . Howā€™s everyone doing?

1 Like