Skip to content

Instantly share code, notes, and snippets.

@KimTrijnh
Created January 14, 2019 15:43
Show Gist options
  • Save KimTrijnh/a64add25013b76055906446075d64a7e to your computer and use it in GitHub Desktop.
Save KimTrijnh/a64add25013b76055906446075d64a7e to your computer and use it in GitHub Desktop.
// tabs is an array of titles of each site open within the window
var Window = function(tabs) {
this.tabs = tabs; // we keep a record of the array inside the object
};
// When you join two windows into one window
Window.prototype.join = function (otherWindow) {
this.tabs = this.tabs.concat(otherWindow.tabs);
return this;
};
// When you open a new tab at the end
Window.prototype.tabOpen = function (tab) {
this.tabs.push('new tab'); // let's open a new tab for now
return this;
};
// When you close a tab
Window.prototype.tabClose = function (index) {
var tabsBeforeIndex = this.tabs.splice(0, index); // get the tabs before the tab
var tabsAfterIndex = this.tabs.splice(1); // get the tabs after the tab
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // join them together
return this;
};
// Let's create three browser windows
var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
// Now perform the tab opening, closing, and other operations
var finalTabs = socialWindow
.tabOpen() // Open a new tab for cat memes
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
.join(workWindow.tabClose(1).tabOpen());
alert(finalTabs.tabs);
//SPLICE(INDEX,NUM) return a spliced array & change the original array. So tabsAfterIndex should go with 1 instead of index.
//Another principle of functional programming is to always declare your dependencies explicitly.
//The function is easier to test, you know exactly what input it takes, and it won't depend on anything else in your program.
@KimTrijnh
Copy link
Author

KimTrijnh commented Jan 15, 2019

5. Refactor Global Variables Out of Functions (FFC_FP)

Functional programming: is centered around a theory of functions.
Functions are considered First Class Objects. can saved in variables, stored in an object, or passed as function arguments.
Functional programming is all about creating and using non-mutating functions. eq. concat can use for push, slice replace for splice

Functional programming principle:

  • Do not alter varibale, object. Create new and return
  • Declare function arguments.

Advantages:

  • Avoid side effect.
var arr1 = [....];
let arr2 = arr1;
change arr2 => also change arr1. 
let arr2 = [...arr1] // change arr2, arr1 doesn't change

Importance of array methods that don't alter original array.

  • Alter original array: splice, push, sort
  • not alter original array: slice, concat, filter, map, forEach, every ( return true if passed, otherwise false)

Importance of array methods that don't alter original string

6. Use the map Method to Extract Data from an Array

map method creates a new array (without changing the original one) after applying a callback function to every element
array.map(function(currentValue, index, arr), thisValue)

var rating = [];
rating =  watchList.map(function(obj){return {title:obj['Title'], rating:obj['imdbRating']}})

7. Implement map on a Prototype

map is a pure function, and its output depends solely on its inputs. Plus, it takes another function as its argument.
A pure function is allowed to alter local variables defined within its scope, although, it's preferable to avoid that as well.

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

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
this.forEach(function(i){
  newArray.push(callback(i))
})
  // Add your code above this line
  return newArray;
};
var new_s = s.myMap(function(item){
  return item * 2;
});

8. Implement the filter Method on a Prototype

-with for loop

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


Array.prototype.myFilter = function(callback){
  var newArray = [];
  // Add your code below this line
//use for loop
  for(let i=0;i<this.length;i++) {
    if(callback(this[i]) ===true) {
      newArray.push(this[i]); }
       }
//use forEach method
 this.forEach(function (item) {if(callback(item) === true) { newArray.push(item);}});
  // Add your code above this line
  return newArray;

};

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

9. Use the reduce Method to Analyze Data

The reduce method allows for more general forms of array processing, and it's possible to show that both filter and map can be derived as a special application of reduce.

10. Sort method

Need more work on it.
it mentions about comparefunction function(a,b) {return a-b}

11. Return a Sorted Array Without Changing the Original Array

Sort method has side effect as it changes the order of the elements in the original array

ways to copy array and make a new array:

  • newarr = arr.concat([ ]) // concat with empty array return new array
  • newArr = arr.slice( ) // slice without parametes, take whole array.

Chú ý: function phải được return value, nếu không sẽ ra kết quả undefined

12. Split a String into an Array Using the split Method

  • str.plit(delimiter) //return an array
  • can be use with REGEX eg. str.split(/\W/);

13. Combine an Array into a String Using the join Method

arr.join(delimiter) // a string
function sentensify(str) { return str.split(/\W/).join(' '); } sentensify("May-the-force-be-with-you");

14. Apply Functional Programming to Convert Strings to URL Slugs

`
// the global variable, should not change
var globalTitle = "Winter Is Coming";

function urlSlug(title) {
return title.toLowerCase().split(' ').filter((i) => i !== '').join('-');
}

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

15. Every method to Check that Every Element in an Array Meets a Criteria

`
function checkPositive(arr) {
// Add your code below this line
return arr.every((i) => i>0);

// Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);
`

16. some Method to Check that Any Elements in an Array Meet a Criteria

function checkPositive(arr) {
  // Add your code below this line
  return arr.some((i)=> i>0);
  
  // Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);

17. Currying Function

  • currying a function (with n argurments) is restructures a function so it takes one argument, then returns another function that takes the next argument, and so on.
//function add(x,y,z) { return x+y+z}
function add(x) {
 return  function(y) {
    return function(z) {
      return x+y+z;
    }
  }
}
add(10)(20)(30);

@KimTrijnh
Copy link
Author

KimTrijnh commented Jan 15, 2019

`// 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
//filter directed by Christopher 
let chrisMovies = watchList.filter((obj)=> obj['Director'] === 'Christopher Nolan' );

//create Array of imdbrating numbers
let ratingArr = chrisMovies.map((obj) => Number(obj['imdbRating']));

//sum using reduce & caculate the average
var averageRating = (ratingArr.reduce((total,num) => (total +num)))/ratingArr.length;

// Add your code above this line

console.log(averageRating); `

@KimTrijnh
Copy link
Author

INTERMEDIATE JS ALGORITHM

Make Person

var Person = function(firstAndLast) {
  // Complete the method below and implement the others similarly

  this.getFullName = function() {
       return firstAndLast;
  };
  this.getFirstName = function() {
   return firstAndLast.split(' ')[0];
  }
  this.getLastName = function() {
   return firstAndLast.split(' ')[1];
  }
  this.setFirstName = function(first) {
    firstAndLast = first + ' ' + firstAndLast.split(' ')[1];
  }
  this.setLastName = function(last) {
    firstAndLast = firstAndLast.split(' ')[0] + ' ' + last;
  }
  this.setFullName = function(newName) {
    firstAndLast = newName;
  }
  return firstAndLast;
};

var bob = new Person('Bob Ross');
bob.getFullName();

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