Skip to content

Instantly share code, notes, and snippets.

@jaeyson
Last active July 20, 2019 11:27
Show Gist options
  • Save jaeyson/3659e7070cc511391e5fdecb6199eca2 to your computer and use it in GitHub Desktop.
Save jaeyson/3659e7070cc511391e5fdecb6199eca2 to your computer and use it in GitHub Desktop.
FCC JS Challenges. lately realized that all of my previous completed puzzles are gone. oh boy, time to move on.

Javascript Algorithms And Data Structures Certification (300 hours)

Basic Algorithm Scripting

Chunky Monkey

function chunkArrayInGroups(arr, size) {
  let divisor = Math.floor(arr.length/size);
  let lastElem = divisor*size;
  let result = [];

  for(let i=0,j=0;i<divisor;i++,j+=size) {
    if(i>0) {
      result.push(arr.slice(j, (j+size)));
    } else {
      result.push(arr.slice(j, size));
    }
  }

  if((arr.length%size) != 0) {
    result.push(arr.slice(lastElem));
  }   return result;
}

console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2))
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3))
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)) //BUG!!!
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4))
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3))
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4))
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2))

// for loop, size, .slice, .push
// Math.floor(5/2) //2 <-- 2.5


// chunkArrayInGroups(["a", "b", "c", "d"], 2)
// should return [["a", "b"], ["c", "d"]]

// chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)
// should return [[0, 1, 2], [3, 4, 5]]

// chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)
// should return [[0, 1], [2, 3], [4, 5]]

// chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)
// should return [[0, 1, 2, 3], [4, 5]]

// chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)
// should return [[0, 1, 2], [3, 4, 5], [6]]

// chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)
// should return [[0, 1, 2, 3], [4, 5, 6, 7], [8]]

// chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)
// should return [[0, 1], [2, 3], [4, 5], [6, 7], [8]]
function sumPrimes(num) {
let arr = [];
let a;
let b = genPrime();
let inc = 1;
function checkPrime(n) {
if (isNaN(n) || !isFinite(n) || n%1 || n<2) return false;
var m = Math.sqrt(n);
for (var i=2;i<=m;i++) if (n%i==0) return false;
return true;
}
function *genPrime() {
var count = 0;
while(1) {
if(checkPrime(count)) yield count;
count++;
}
}
while(inc<num) {
arr.push(b.next().value);
inc++
}
a = arr.filter(x => x <= num);
return a.reduce((x,y) => x+y);
// for(let i=6;i<=num;i++) {arr.push(i); }
// a = arr.filter(x => x%2!=0);
// b = a.filter(x => x%3!=0);
// c = b.filter(x => x%4!=0);
// d = c.filter(x => x%5!=0);
// e = d.filter(x => x%7!=0);
// f = e.filter(x => x%9!=0);
// g = f.filter(x => x%11!=0);
// f = [2,3,5,7,...e].filter(x => x <= num)
// g = f.reduce((x,y) => x+y);
// return f;
}
console.log(sumPrimes(10));
console.log(sumPrimes(977));

Javascript Algorithms And Data Structures Certification (300 hours)

Functional Programming

Use the map Method to Extract Data from an Array

// the global variable
var watchList = [
                 {  
                   "Title": "Inception",
                   "Year": "2010",
                   "Rated": "PG-13",
                   "Released": "16 Jul 2010",
                   "Runtime": "148 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Christopher Nolan",
                   "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
                   "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
                   "Language": "English, Japanese, French",
                   "Country": "USA, UK",
                   "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Rated": "PG-13",
                   "Released": "07 Nov 2014",
                   "Runtime": "169 min",
                   "Genre": "Adventure, Drama, Sci-Fi",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan, Christopher Nolan",
                   "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
                   "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
                   "Language": "English",
                   "Country": "USA, UK",
                   "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "The Dark Knight",
                   "Year": "2008",
                   "Rated": "PG-13",
                   "Released": "18 Jul 2008",
                   "Runtime": "152 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
                   "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
                   "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
                   "Language": "English, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
                   "Metascore": "82",
                   "imdbRating": "9.0",
                   "imdbVotes": "1,652,832",
                   "imdbID": "tt0468569",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Batman Begins",
                   "Year": "2005",
                   "Rated": "PG-13",
                   "Released": "15 Jun 2005",
                   "Runtime": "140 min",
                   "Genre": "Action, Adventure",
                   "Director": "Christopher Nolan",
                   "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
                   "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
                   "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
                   "Language": "English, Urdu, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
                   "Metascore": "70",
                   "imdbRating": "8.3",
                   "imdbVotes": "972,584",
                   "imdbID": "tt0372784",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Avatar",
                   "Year": "2009",
                   "Rated": "PG-13",
                   "Released": "18 Dec 2009",
                   "Runtime": "162 min",
                   "Genre": "Action, Adventure, Fantasy",
                   "Director": "James Cameron",
                   "Writer": "James Cameron",
                   "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
                   "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
                   "Language": "English, Spanish",
                   "Country": "USA, UK",
                   "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
                   "Metascore": "83",
                   "imdbRating": "7.9",
                   "imdbVotes": "876,575",
                   "imdbID": "tt0499549",
                   "Type": "movie",
                   "Response": "True"
                }
];

// Add your code below this line

var rating = [];
// for(var i=0; i < watchList.length; i++){
//   rating.push({title: watchList[i]["Title"],  rating: watchList[i]["imdbRating"]});
// }
watchList.map((x) => {
  rating.push({"title": x.Title, "rating": x.imdbRating});
});

// Add your code above this line

console.log(rating);

Implement map on a Prototype

// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
  
  // "this" is being called outside
  // of this function
  for(let item of this) {
    newArray.push(callback(item));
  }
  // Add your code above this line
  return newArray;

};

var new_s = s.myMap(function(item){
  return item * 2;
});

console.log(new_s);

// new_s should equal [46, 130, 196, 10].
// Your code should not use the map method.

Use the filter Method to Extract Data from an Array

// the global variable
var watchList = [
                 {  
                   "Title": "Inception",
                   "Year": "2010",
                   "Rated": "PG-13",
                   "Released": "16 Jul 2010",
                   "Runtime": "148 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Christopher Nolan",
                   "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
                   "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
                   "Language": "English, Japanese, French",
                   "Country": "USA, UK",
                   "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Rated": "PG-13",
                   "Released": "07 Nov 2014",
                   "Runtime": "169 min",
                   "Genre": "Adventure, Drama, Sci-Fi",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan, Christopher Nolan",
                   "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
                   "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
                   "Language": "English",
                   "Country": "USA, UK",
                   "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "The Dark Knight",
                   "Year": "2008",
                   "Rated": "PG-13",
                   "Released": "18 Jul 2008",
                   "Runtime": "152 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
                   "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
                   "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
                   "Language": "English, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
                   "Metascore": "82",
                   "imdbRating": "9.0",
                   "imdbVotes": "1,652,832",
                   "imdbID": "tt0468569",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Batman Begins",
                   "Year": "2005",
                   "Rated": "PG-13",
                   "Released": "15 Jun 2005",
                   "Runtime": "140 min",
                   "Genre": "Action, Adventure",
                   "Director": "Christopher Nolan",
                   "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
                   "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
                   "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
                   "Language": "English, Urdu, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
                   "Metascore": "70",
                   "imdbRating": "8.3",
                   "imdbVotes": "972,584",
                   "imdbID": "tt0372784",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Avatar",
                   "Year": "2009",
                   "Rated": "PG-13",
                   "Released": "18 Dec 2009",
                   "Runtime": "162 min",
                   "Genre": "Action, Adventure, Fantasy",
                   "Director": "James Cameron",
                   "Writer": "James Cameron",
                   "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
                   "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
                   "Language": "English, Spanish",
                   "Country": "USA, UK",
                   "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
                   "Metascore": "83",
                   "imdbRating": "7.9",
                   "imdbVotes": "876,575",
                   "imdbID": "tt0499549",
                   "Type": "movie",
                   "Response": "True"
                }
];

// Add your code below this line

let filteredList = [];

watchList.filter(x => {
  return x.imdbRating >= 8.0;
}).map(x => {
  filteredList.push({"title": x.Title, "rating": x.imdbRating});
});
// Add your code above this line

console.log(filteredList); 

Implement the filter Method on a Prototype

// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback, context){
  var newArray = [];
  // Add your code below this line
  for (var i = 0; i < this.length; i++) {
      if (callback.call(context, this[i], i, this))
          newArray.push(this[i]);
  }
  // Add your code above this line
  return newArray;

};

var new_s = s.myFilter(function(item){
  return item % 2 === 1;
});

console.log(new_s)

Return Part of an Array Using the slice Method

function sliceArray(anim, beginSlice, endSlice) {
  // Add your code below this line
  return anim.slice(beginSlice,endSlice);
  // Add your code above this line
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
console.log(sliceArray(inputAnim, 1, 3));

Remove Elements from an Array Using slice Instead of splice

function nonMutatingSplice(cities) {
  // Add your code below this line
  return cities.slice(0,3);
  
  // Add your code above this line
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);

Combine Two Arrays Using the concat Method

function nonMutatingConcat(original, attach) {
  // Add your code below this line
  return original.concat(attach);
  // Add your code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
console.log(nonMutatingConcat(first, second));

Use the reduce Method to Analyze Data

// the global variable
var watchList = [
                 {  
                   "Title": "Inception",
                   "Year": "2010",
                   "Rated": "PG-13",
                   "Released": "16 Jul 2010",
                   "Runtime": "148 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Christopher Nolan",
                   "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
                   "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
                   "Language": "English, Japanese, French",
                   "Country": "USA, UK",
                   "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Rated": "PG-13",
                   "Released": "07 Nov 2014",
                   "Runtime": "169 min",
                   "Genre": "Adventure, Drama, Sci-Fi",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan, Christopher Nolan",
                   "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
                   "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
                   "Language": "English",
                   "Country": "USA, UK",
                   "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "The Dark Knight",
                   "Year": "2008",
                   "Rated": "PG-13",
                   "Released": "18 Jul 2008",
                   "Runtime": "152 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
                   "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
                   "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
                   "Language": "English, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
                   "Metascore": "82",
                   "imdbRating": "9.0",
                   "imdbVotes": "1,652,832",
                   "imdbID": "tt0468569",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Batman Begins",
                   "Year": "2005",
                   "Rated": "PG-13",
                   "Released": "15 Jun 2005",
                   "Runtime": "140 min",
                   "Genre": "Action, Adventure",
                   "Director": "Christopher Nolan",
                   "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
                   "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
                   "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
                   "Language": "English, Urdu, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
                   "Metascore": "70",
                   "imdbRating": "8.3",
                   "imdbVotes": "972,584",
                   "imdbID": "tt0372784",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Avatar",
                   "Year": "2009",
                   "Rated": "PG-13",
                   "Released": "18 Dec 2009",
                   "Runtime": "162 min",
                   "Genre": "Action, Adventure, Fantasy",
                   "Director": "James Cameron",
                   "Writer": "James Cameron",
                   "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
                   "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
                   "Language": "English, Spanish",
                   "Country": "USA, UK",
                   "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
                   "Metascore": "83",
                   "imdbRating": "7.9",
                   "imdbVotes": "876,575",
                   "imdbID": "tt0499549",
                   "Type": "movie",
                   "Response": "True"
                }
];
// Add your code below this line
let arr = [];
let a = watchList.filter(x => x.Director == "Christopher Nolan");
a.map(x => arr.push(parseFloat(x.imdbRating)));
let b = arr.reduce((x,y) => x+y);
let averageRating = b/arr.length;
// Add your code above this line
console.log(averageRating); 

Return a Sorted Array Without Changing the Original Array

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
  let result = [];
  return result.concat(arr).sort();
  
  // Add your code above this line
}
console.log(nonMutatingSort(globalArray));
console.log(globalArray);

Split a String into an Array Using the split Method

function splitify(str) {
  // Add your code below this line
  return str.split(/[\.\W\s]/g);
  
  // Add your code above this line
}
console.log(splitify("Hello World,I-am code"));
console.log(splitify("This.is.a-sentence"));
console.log(splitify("Earth-is-our home"));
console.log(splitify("Hello World,I-am code"));

// splitify("Hello World,I-am code") should return ["Hello", "World", "I", "am", "code"].
// splitify("Earth-is-our home") should return ["Earth", "is", "our", "home"].
// splitify("This.is.a-sentence") should return ["This", "is", "a", "sentence"].

Combine an Array into a String Using the join Method

function sentensify(str) {
  // Add your code below this line
  return str.split(/[\.\W\s]/g).join(" ");
  
  // Add your code above this line
}
console.log(sentensify("May-the-force-be-with-you"));
console.log(sentensify("There,has,been,an,awakening"));
console.log(sentensify("The.force.is.strong.with.this.one"));
console.log(sentensify("May-the-force-be-with-you"));
console.log(sentensify("May-the-force-be-with-you"));

// sentensify("May-the-force-be-with-you") should return a string.
// sentensify("May-the-force-be-with-you") should return "May the force be with you".
// sentensify("The.force.is.strong.with.this.one") should return "The force is strong with this one".
// sentensify("There,has,been,an,awakening") should return "There has been an awakening".

Apply Functional Programming to Convert Strings to URL Slugs

// the global variable
var globalTitle = "Winter Is Coming";

// Add your code below this line
function urlSlug(title) {
  // return title.split(/[\s+\W\.]/g).join("-").toLowerCase();
  return title.trim().split(/\s+/g).join("-").toLowerCase();
}
// Add your code above this line

var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"

console.log(urlSlug(globalTitle));
console.log(urlSlug("Hold The Door"));
console.log(urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone"));
console.log(urlSlug(" Winter Is  Coming"));
console.log(urlSlug("Winter Is Coming"));

// The globalTitle variable should not change.
// Your code should not use the replace method for this challenge.
// urlSlug("Winter Is Coming") should return "winter-is-coming".
// urlSlug(" Winter Is  Coming") should return "winter-is-coming".
// urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone") should return "a-mind-needs-books-like-a-sword-needs-a-whetstone".
// urlSlug("Hold The Door") should return "hold-the-door".

Javascript Algorithms And Data Structures Certification (300 hours)

Intermediate Algorithm Scripting

Sum All Numbers in a Range

function sumAll(arr) {
  let a = arr[0];
  let b = arr[1];

  function inc(start, end) {
    if(start === end) return [start];
    return [start, ...inc(start + 1, end)];
  }

  function dec(start, end) {
    if(start === end) return [start];
    return [start, ...dec(start - 1, end)];
  }

  if(a < b) {
    return inc(a,b).reduce((a,b) => a+b);
  } else {
    return dec(a,b).reduce((a,b) => a+b);
  }
}

console.log(sumAll([1, 4]));
console.log(sumAll([10, 5]));
console.log(sumAll([5, 10]));
console.log(sumAll([4, 1]));

// sumAll([1, 4]) should return a number.
// sumAll([1, 4]) should return 10.
// sumAll([4, 1]) should return 10.
// sumAll([5, 10]) should return 45.
// sumAll([10, 5]) should return 45.

Diff Two Arrays

function diffArray(arr1, arr2) {
  var newArr = [];
  // Same, same; but different.
  let a = [...arr1, ...arr2];
  let b = a.filter((x,y) => a.indexOf(x) != y); //[1,2,3,5]
  let c = a.filter( x => b[b.indexOf(x)] != x);
  return c;
}

console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));

Seek and Destroy

function destroyer(arr) {
  // Remove all the values
  var args = Array.prototype.slice.call(arguments);
  arguments.length;

  let arrays = args[0];
  let params =  args.slice(1);
  // for(let i=0;i<arrays.length;i++) {
  //   for(let j=0;j<params.length;j++) {
  //     if(arrays[i] == params[j]) {
  //       console.log(result.splice(params.indexOf(j),1));
  //     }
  //   }
  // }
  return arrays.filter(x => !arrays.includes(params[params.indexOf(x)]));
  // a.concat([1,2,3,4].filter(x => x%2==0));
  // a.push([1,2,3,4].filter(x => x%2==0));
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
console.log(destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3));
console.log(destroyer([3, 5, 1, 2, 2], 2, 3, 5));
console.log(destroyer([2, 3, 2, 3], 2, 3));
console.log(destroyer(["tree", "hamburger", 53], "tree", 53));
console.log(destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan"));

Wherefore art thou

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // ugghh wont work
  // let a = [{ first: "Romeo", last: "Montague" },
  //          { first: "Mercutio", last: null },
  //          { first: "Tybalt", last: "Capulet" }];
  // Object.keys(a[1]); //["first", "last"]
  // a[1].hasOwnProperty("last"); //true
  // for(let i=0;i<a.length;i++) {
  //   arr.push(a.filter(x => {
  //     a[i].hasOwnProperty(Object.keys(a[i]));
  //   }));
  // }
  // let b = Object.keys(source); //["last"]
  let keys = Object.keys(source);
  collection.forEach( obj => {
    if(keys.every( props => {return obj[props] === source[props];})) {
      arr.push(obj);
    }
  });

  // Only change code above this line
  return arr;
}

console.log(whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }));
console.log(whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}));
console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 }));
console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }));
console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }));
console.log(whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }));


// whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })
// should return [{ first: "Tybalt", last: "Capulet" }].

// whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 })
//should return [{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }].

// whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })
//should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }].

// whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 })
//should return [{ "apple": 1, "bat": 2, "cookie": 2 }].

// whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })
//should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }].

// whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3})
//should return []

Spinal Tap Case

function spinalCase(str) {
  // "It's such a fine line between stupid, and clever."
  // --David St. Hubbins
  str = str.replace(/([a-zA-Z](?=[A-Z]))/g, '$1 ');
  return str.toLowerCase().replace(/\ |\_/g, '-');
}

console.log(spinalCase('This Is Spinal Tap'));
console.log(spinalCase("thisIsSpinalTap"));
console.log(spinalCase("The_Andy_Griffith_Show"));
console.log(spinalCase("Teletubbies say Eh-oh"));
console.log(spinalCase("AllThe-small Things"));

// spinalCase("This Is Spinal Tap")
//should return "this-is-spinal-tap".

// spinalCase("thisIsSpinalTap")
//should return "this-is-spinal-tap".

// spinalCase("The_Andy_Griffith_Show")
//should return "the-andy-griffith-show".

// spinalCase("Teletubbies say Eh-oh")
//should return "teletubbies-say-eh-oh".

// spinalCase("AllThe-small Things")
//should return "all-the-small-things".

Pig Latin

const vowels = ["a","e","i","o","u"];

function translatePigLatin(str) {
  // let chop = str.slice(0,2);
  // let rest = str.slice(2);
  // let firstLetterVowel = str.slice(0,1);

  if(!vowels.includes(str[0])) {
    return toConsonant(str)
  } else { return toVowel(str) }
}

function toConsonant(str) {
  let word = Array.from(str);
  let arr = [];
  let rest;

  for(let x of word) {
    if(!vowels.includes(x)) {
      arr.push(x)
    } else { break }
  }

  rest = word.slice(arr.length);
  arr.unshift(rest);
  arr.push("ay");
  return arr.flat().join("")

}

function toVowel(str) {
  return str + "way";
}

console.log(translatePigLatin("consonant"));
console.log(translatePigLatin("california"));
console.log(translatePigLatin("paragraphs"));
console.log(translatePigLatin("glove"));
console.log(translatePigLatin("algorithm"));
console.log(translatePigLatin("eight"));

// translatePigLatin("california") should return "aliforniacay".
// translatePigLatin("paragraphs") should return "aragraphspay".
// translatePigLatin("glove") should return "oveglay".
// translatePigLatin("algorithm") should return "algorithmway".
// translatePigLatin("eight") should return "eightway".

Search and Replace

function myReplace(str, before, after) {
  // let regex = /`${before}`/i;
  let firstLetter =  before[0];
  let anotherFirstLetter = after[0];
  // arguments[2].charAt(0).toUpperCase();
  // let change = arguments[2].charAt(arguments[2].length-1).toUpperCase();
  let updatedLetter;
  if(firstLetter == firstLetter.toUpperCase()){;
    updatedLetter = after.replace(anotherFirstLetter, anotherFirstLetter.toUpperCase());
    return str.replace(before, updatedLetter)
  } else { return str.replace(before, after) }
  // arguments[2].charAt(0).toUpperCase();
  // return str.replace(before,after);
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));
console.log(myReplace("Let us go to the store", "store", "mall"));
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"));
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"));
console.log(myReplace("His name is Tom", "Tom", "john"));
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"));

DNA Pairing

function pairElement(str) {
  let a;
  let y = {
    A: "T",
    T: "A",
    C: "G",
    G: "C"
  }
  return str.split("").map(x => {
    return [ x, y[x] ]
  });
}

console.log(pairElement("GCG"));
console.log(pairElement("ATCGA"));
console.log(pairElement("TTGAG"));
console.log(pairElement("CTCTA"));

Missing Letters

function fearNotLetter(str) {
  // "a".charCodeAt(0); //97  <--  97 + 25others = 122
  // "z".charCodeAt(0); //122
  // String.prototype.charCodeAt(index);
  // String.fromCharCode(charCode);
  for(let i=str.charCodeAt(0);i<=str.charCodeAt(str.length-1);i++) {
    let letter = String.fromCharCode(i);
    if(str.indexOf(letter) < 0) {
      return letter
    }
  }
}

console.log(fearNotLetter("abce"));
console.log(fearNotLetter("abcdefghjklmno"));
console.log(fearNotLetter("stvwx"));
console.log(fearNotLetter("bcdf"));
console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz"));

Sorted Union

function uniteUnique(arr) {
  let flat = arr.concat(...arguments);
  return [...new Set(flat)]
}

console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));
console.log(uniteUnique([1, 3, 2], [1, [5]], [2, [4]]));
console.log(uniteUnique([1, 2, 3], [5, 2, 1]));
console.log(uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]));

Convert HTML Entities

function convertHTML(str) {
  // &colon;&rpar;

  let codeHTML = {
    "38": "&amp;",
    "60": "&lt;",
    "62": "&gt;",
    "34": "&quot;",
    "39": "&apos;"
  };

  let entityHTML = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    "\"": "&quot;",
    "\'": "&apos;"
  };
  let regex = /[^\w\s]/g;
  let arr = [];

  //let string = x.match(regex).join("").codePointAt().toString()
  //return str.replace(regex, "&quot;")
  str.split("").map(x => {
    if(entityHTML.hasOwnProperty(x)) {
      arr.push(entityHTML[x])
    } else { arr.push(x) }
    //return x.replace(regex, entityHTML[x.match(regex)])
  });

  return arr.join("");
  //str.map(x => {
    //return x.replace(regex, entityHTML[x])
    //if(entityHTML[x]) {
    //  return entityHTML[x]
    //} else {
    //  return x
    //}
  //});
}

console.log(convertHTML("Dolce & Gabbana &&"));
console.log(convertHTML("Hamburgers < Pizza < Tacos"));
console.log(convertHTML("Sixty > twelve"));
console.log(convertHTML('Stuff in "quotation marks"'));
console.log(convertHTML("Schindler's List"));
console.log(convertHTML("<>"));
console.log(convertHTML("abc"));

Sum All Odd Fibonacci Numbers

function sumFibs(num) {
  let arr = [1, 1];
  let oddFilter;
  let sumOdd;

  for (let i = 2; i < num; i++) {
    if(arr[i-1] <= num) {
      arr.push(arr[i-1]+ arr[i-2])
    } else {
      break;
    }
  }
  oddFilter = arr.filter(x => x%2!=0);
  sumOdd = oddFilter.filter(x => x <= num);
  return sumOdd.reduce((x,y) => x+y)

  //return arr.filter(x => {
  //  return x%2!=0
  //}).reduce((x,y) => x+y);
  //function *fibonacci(n, current = 1, next = 1) {
  //  if (n === 0) {
  //    return current;
  //  }
  //  yield current;
  //  yield *fibonacci(n-1, next, current + next);
  //}

  //return [...fibonacci(num)].filter(x => x <= num && x % 2 != 0).reduce((x,y) => {
  //  return x + y
  //})
}

console.log(sumFibs(1));
console.log(sumFibs(1000));
console.log(sumFibs(4000000));
console.log(sumFibs(4));
//console.log(sumFibs(5));
//console.log(sumFibs(10));
//console.log(sumFibs(20));
console.log(sumFibs(75024));
console.log(sumFibs(75025));

// For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.

// sumFibs(1) should return a number.
// sumFibs(1000) should return 1785.
// sumFibs(4000000) should return 4613732.
// sumFibs(4) should return 5.
// sumFibs(75024) should return 60696.
// sumFibs(75025) should return 135721.

Sum All Primes

let sumPrime = (num) => {
  let arr = [];
  for(let i = 2; i <= num; i++) {
    arr.push(isPrime(i));
  }

  return arr.reduce((x,y) => {
    return x + y;
  })
}

let isPrime = (num) => {
  //if(num < 2) return false;
  if(num < 2) return 0;

  let q = parseInt(Math.sqrt(num));

  for(let i = 2; i <= q; i++) {
    if(num % i == 0) {
      return 0;
    }
  }

  return num;
}

console.log(sumPrime(10));
console.log(sumPrime(20));

Drop it

Steamroller

Binary Agents

Everything Be True

Arguments Optional

Make a Person

Map the Debris

Javascript Algorithms And Data Structures Certification (300 hours)

JavaScript Algorithms and Data Structures Projects

Palindrome Checker

Roman Numeral Converter

Caesars Cipher

Telephone Number Validator

Cash Register

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment