ReactJS

ReactJS is a Javascript library that is built on the premise of declarative and reusable components.  It’s the view layer in MVC and can be used with other frameworks or libraries to build applications.

  • one-way data binding: example – when you type in an input field, it doesn’t directly change the state of that component.  Instead, it updates the data model, which causes the UI to be updated.
  • virtual DOM: A virtual representation of the real DOM that React uses to intelligently re-render each component.  Each time the data changes in the app, a new Virtual DOM  is created, and the differences between the new Virtual DOM and the previous Virtual DOM will be updated in the real DOM.  Read more.
  • JSX:  XML/HTML-like syntax used by React that extends ECMAScript so that XML/HTML-like text can co-exist with JavaScript/React code.  (use Babel to transpile JSX and ES6 into Javascript).  JSX expressions are shorthand for ‘React.createElement’.

Components: 

  • A React app is a tree of nested components.
  • Props and state control each component.
  • Components must implement render.
  • Use class components for stateful components.

Screen Shot 2017-12-16 at 5.05.59 PM

  • Don’t use class for stateless components.

Screen Shot 2017-12-16 at 5.07.12 PM

Events: 

  • Events are created inside components and are added to their corresponding render function.  (e.g. onListItemHover event above).

Props:

  • Props contain information set by the parent component and can be passed to the child component(s). It’s the equivalent of $scope in Angular).
  • When a component is rendered, it can access its props using this.props.
  • Props are immutable.

State:

  • State is what makes your app interactive.
  • In general, you should initialize state in the constructor, and then call setState when you want to change it.
  • State is mutable.
  • State should be held at the top-most component that needs access to it.
  • Components manage their own state.
  • Initial values can be set for state.
  • State can be passed from parent components to child components as props.
    • Example:  Component A is parent of Component B.  When component B is clicked on, it updates state on component A.  In order for this to happen:
      1. Define a function that updates state on component A.
      2. Pass the function as a prop to component B.
      3. Invoke the function when B is clicked on.

Lifecycle Methods:

React components have a lifecycle, and you’re able to access specific phases of that lifecycle to update certain parts of each component.

  • Component creation: 
    • componentWillMount: called before the render method is executed.
    • componentDidMount: called after render method is executed.
      • example: You’re creating an application that streams music from the SoundCloud API as soon as a client connects to your website.  You would use componentDidMount to make that Ajax request to SoundCloud to ensure you have the song data you need once the application renders.
  • State changes:
    • shouldComponentUpdate
    • componentWillUpdate
    • componentDidUpdate

Read more.

Advertisements
ReactJS

Angular

Angular is an MVW (model-view-whatever) framework for properly architected single-page applications.   It’s opinionated, declarative, has two-way binding, and allows separation of presentation and business logic.

Angular 1 and 2 are quite different.

Modules:

Module are top-level containers for different parts of the application.

Controllers:

  • Controllers build logic for a particular view
  • Controllers configure and manage the $scope object.
  • Controllers make your components stateful.  Without controllers, your component is stateless.

Screen Shot 2017-12-15 at 10.46.47 AM

In example above, controller is not part of a component so to access the attributes, you have to use $scope.  If the controller is within a component, you have to use ‘this’ (and $ctrl in template). 

Scope: 

  • In Angular 1, you access scope using $scope.
  • In Angular 2, you access scope using this (because $scope and controllers don’t exist) and $ctrl.  (It’s similar to props in React)

Factories/Services:

  • Factories and services are objects that you can register with Angular so their data and behavior can be shared among different parts of the app. (e.g. registering an API with Angular so it can be accessed everywhere in the app)
  • The main difference between factories and services is that services are instantiated with the ‘new’ keyword so you do not need to return the object.
  • Services allow the use of ES6 classes because they are constructor functions.

Components:

Angular 1.x uses components but Angular 2 is entirely component-based.

  • In a component, there is always a template, which is used to render your view.
  • If you’re passing data from or to a component, use data binding.
    • When using binding, specify what you want the attribute to be treated as:
      • ‘@’ : strings
      • ‘<‘ :  one-way binding. Used to pass variables down.
      • ‘=’:  two-way binding.  Not very common.
      • ‘&’: methods or functions
  • Use ‘this’ keyword to access scope within controller in component.

Screen Shot 2017-12-15 at 12.14.01 PM

Screen Shot 2017-12-15 at 12.27.25 PM

data binding is used above to pass the ‘item’ variable from ‘todoList’ component to ‘entry’ subcomponent.

Directives:

Directives supercharge your HTML by giving it angular power!

There are four categories of directives:

  1. attribute (most commonly used)
  2. class name
  3. comment
  4. element (components are basically element directives)

Filters: 

Angular offers filters that make your app dynamic.  Some filters include: JSON, uppercase, lowercase, etc.

Syntax: 

  • built-in directives are prefixed with ‘ng’ in Angular 1.  (e.g. ng-click).  No ‘ng’ in Angular 2.
  • To present something to a user, use double curly braces {{ }}
  • When you want something to be invoked by Angular, use double quotes.

AngularJS Resources:

 

 

Angular

Rock Paper Scissors

To solve this problem recursively, think of the game as a tree and you want to traverse all possible solutions depth-first.  That means going all the way down one branch first before moving back up to evaluate the previous level(s).

Screen Shot 2017-12-10 at 6.19.47 PM

Recursive Solution:

var rockPaperScissors = function(n) {
  var output = [];
  var choices = ['rock', 'paper', 'scissors'];
  n = n || 3;

  var makeCombo = function(movesPlayed, roundsLeft) {
    if (roundsLeft === 0){
      output.push(movesPlayed);
    } else {
       for (var i = 0; i < choices.length; i++) {
         makeCombo(movesPlayed.concat(choices[i]), roundsLeft - 1);
       }
    }
  }
  makeCombo([], n);
  return output;
};

 

Order of execution: 

1. makeCombo([], 3)
2. makeCombo([‘rock’], 2);
3. makeCombo([‘rock rock’], 1);
4. makeCombo([‘rock paper’], 1);
5. makeCombo([‘rock scissors’], 1);
6. makeCombo([‘rock rock rock’], 0);
7. push [‘rock rock rock’] to output
8. makeCombo([‘rock rock paper’], 0);
9. push [‘rock rock paper’] to output
10. makeCombo([‘rock rock scissors’], 0);
11. push [‘rock rock scissors’] to output

12. makeCombo([‘paper’], 2);

..

…. makeCombo([‘scissors’], 2);

 

 

 

Rock Paper Scissors

‘this’ keyword

‘this’ in Global Context:

  • ‘this’ refers to window.

‘this‘ in a function call: 

  • In most cases, the value of a function’s ‘this’ argument is determined by how the function is called.  This means the ‘this’ value may be different each time a function is executed.
  • In “use strict” mode, ‘this’ is defaulted to undefined and prevents us from assigning values to undefined, and accidentally creating global variables.

‘this’ in a constructor call:

  • When a function is called as a constructor (with a ‘new’ keyword), a new object is created and set as the function’s ‘this’ argument.
function Person (firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

const person = new Person('John', 'Doe');

console.log(person) // { firstName: 'John', lastName: 'Doe' }

‘this’ in method call:

  • When a function is called as a method of an object, that function’s this argument is set to the object the method is called on. That object is called the receiver of the function call.
  • Oftentimes, the receiver gets lost when we invoke a method as a function. This happens particularly often when passing a method as a callback to another function. (example below – ‘this’ context is lost when assigning method to greet)
const person = {
   firstName: 'John',
   sayHi() {
     console.log(`Hi, my name is ${this.firstName}!`);
   }
};

const greet = person.sayHi;
greet(); // Hi, my name is undefined!
  • Use a wrapper function or .bind method to workaround this problem.

Specify ‘this’ using .call() or .apply():

  • Use .call and .apply to call a function with an explicit ‘this’ argument
  • .call accepts arguments as a comma separated list
  • .apply accepts arguments as an array.
const numbers = [10, 20, 30, 40, 50]

const slice1 = numbers.slice(1, 4); //syntactic sugar for the following:
const slice2 = numbers.slice.call(numbers, 1, 4);
const slice3 = numbers.slice.apply(numbers, [1, 4]);

// slice1, slice2, slice3 all return [20, 30, 40]

Hard-bind a function’s ‘this’ using .bind():

  • permanently tie a function’s ‘this’ argument to a specific value. It creates a new bound function that calls the original function with the provided ‘this’ argument, no matter how that bound function is called.
const person = {
   firstName: 'John',
   sayHi() {
     console.log(`Hi, may name is ${this.firstName}!`);
   }
};

const greet = person.sayHi.bind(person);
greet(); // Hi, my name is John!

const otherPerson = {
   firstName: 'Jane'
};

greet.call(otherPerson); // Hi, my name is John! 

‘this’ can be captured with an Arrow Function (ES6):

  • An arrow function doesn’t have its own ‘this’. Instead, it uses the ‘this’ value from its enclosing execution context.
  • When an arrow function is created, it permanently captures the surrounding ‘this’ value. Neither .call() nor .apply() can change the ‘this’ value later.
  • Arrow functions cannot be used as constructors.
  • Solves issues of incorrect ‘this’ values within callback functions.
const counter = {
  count: 0,
  incrementPeriodically() {
    setInterval(() => {
      console.log(this.count++);
    }, 1000);
  }
};

counter.incrementPeriodically();

// 'this' stays bound to counter object inside setInterval.

‘this’ in classes:

  • Within the constructor of a class, this refers to the newly created object.  Within a method, however, this might refer to another value if the method is called as an ordinary function. Just like any other object method, class methods can lose their intended receiver this way.
class Person {
  constructor (firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.sayHi = this.sayHi.bind(this);
  } 

  sayHi() {
    console.log(`Hi, my name is ${this.firstName}!`);
  } 
}

const person = new Person('John', 'Doe'); 
const greet = person.sayHi; 

greet(); // Hi, my name is John 
// ('this' is bound to object in constructor)
  • You can also bind this using class fields with arrow functions:
class Person {
  // class field with arrow function
  sayHi = () => {
    console.log(`Hi, my name is ${this.firstName}!`);
  } 
  constructor (firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  } 
}

const person = new Person('John', 'Doe'); 
const greet = person.sayHi; 

greet(); // Hi, my name is John 
// ('this' is bound to instance in class fields w/ arrow functions)

*Use a transpiler like Babel to translate ES6 into ES5 if using class fields and arrow functions.

‘this’ keyword

Pseudoclassical Subclassing

// Class constructor
var Class = function(arg1, arg2) {
  this.arg1 = arg1;
  this.arg2 = arg2;
};

Class.prototype.method = function () {
};
// Subclass constructor
var Subclass = function(arg1, arg2) {
  Class.call(this, arg1, arg2);
  this.arg1 = arg1;
  this.arg2 = arg2;
}

// Delegates fallback prototype to Class's prototype
Subclass.prototype = Object.create(Class.prototype);

// Reseting subclass's constructor since we just overrode it 
Subclass.prototype.constructor = Subclass; 

* Use Object.create to delegate to Class prototype allows us to make a copy of it rather than modifying Class’ prototype when we’re making changes to Subclass’ prototype.

Pseudoclassical Subclassing

Sprint: Subclass Dance Party

Takeaways (to be updated):

  • Always bind event handlers (because you will lose context of ‘this’).
  • If using pseudoclassical pattern, make sure it’s being used in all your files. (e.g. calling new dancerMakerFunction() in init.js).
  • Use jQuery plugins and libraries for special effects.
  • Debugging:
    • Use debugger; inside function to be tested
    • Trace the call stack
    • Hover over variables or code to see what they’re referencing
    • Remember to stop the debugger to execute the rest of the app
Sprint: Subclass Dance Party

Time Complexity

Time complexity:  describes how many operations an algorithm has to do relative to its input size.

slow-growing: runtime does not increase with additional input
fast-growing: runtime increases super fast with additional inputScreen Shot 2017-12-03 at 8.28.33 PM.png
Learn.jpg

O(1):  An algorithm is run in constant time if it requires the same amount of time regardless of the input size.  (e.g. array lookup).

O(logN): runtime decreases at a rate that’s inversely proportional to input size.  (e.g. binary search – narrowing search).

O(n): runtime increases at a rate that’s directly proportional to the input size.  (e.g. a for loop to iterate over every item in an array).

O(n^2): runtime increases at an order of magnitude proportional to the square of its input size.  (e.g. two nested for loops)

O(c^n): With each step the function performs, it’s subsequent step will take longer by an order of magnitude equivalent to a factor of N. (e.g. guessing password combos)

Time Complexity