Angular Injection

Another way to inject services into your AngularJS app is splitting out the injection into a new line. When doing this method, be sure to order your injections in the same order that they are passed into the controller function.

// GOOD
(function() {
angular
.module('app')
.controller('MyTableController', MyTableController);

MyTableController.$inject = [ 'getTable','tablesService','$scope' ];

function MyTableController(getTable, tablesService, $scope) {
console.log("getTable", getTable);
}
})();

// BAD
(function() {
angular
.module('app')
.controller('MyTableController', MyTableController);

MyTableController.$inject = [ 'getTable','$scope','tablesService' ];

function MyTableController(getTable, tablesService, $scope) {
console.log("getTable", getTable);
}
})();

Advertisements

Callbacks to gather data in JavaScript

Callbacks may be a dying breed with the new ES6 inclusion of promises but it’s good to understand the need for a callback.

JavaScript by design is asynchronous to ensure speedy applications. This means that when a line of code is fired, it doesn’t wait for a response before executing the next line of code. But what happens if you need the first line to return in order to use the returned item for the next line of code? This is where callbacks come in most handy.

Creating a function that takes a callback as one of the arguments will provide scope and closure to the line of code that called the function. It’s like sending an enclosed stamped envelope along with your wedding invite in order to get a (reliable) response from the guest you are inviting.

This is really important when gathering data from a database or when the function you are calling parses a text file because these processes can take some time.

Here’s an example of a recent use case that helped my web historian read and return the index file:

http-helpers.js

exports.serveIndex = function(res, asset) {

archive.readIndex(function(data){

res.writeHead(200, this.headers);
res.end(JSON.stringify(data));

});

};

archive-helpers.js

exports.readIndex = function (callback) {

fs.readFile(exports.paths.index, "utf8", function(err, data){

if(err) throw err;

callback(data);

});

};

Time Complexity of Algorithms

While writing out algorithms in code, a programmer must be aware of their drain on the performance that may be passed onto the user experience or aware of the potential drain of CPU usage. A friend recently told me of an infinite (but harmless) loop that the code for their database had and the “damage” was an additional $100k in CPU usage for that machine for the month (because the server was hosted and paid by CPU usage).

Constant Time – O(1)

Increasing the problem size does not change the number of operations.

Examples:

  • Pulling from the top of a stack or from the front of an array. No matter how large the stack or array is, the steps to complete the operations is one.
  • Looking up a value on an object when the key is known.

Linear Time – O(n)

The number of operations is proportional to problem size. The larger the list the longer the operation will take to complete by that n number.

Examples:

  • Finding a single item in an unsorted array
  • Searching for a single value in a linked list
  • ForEach
  • Slice and indexOf is linear in Javascript

Logarithmic Time – O(log c n)

Multiplying the problem size by constant adds the same number operations. How many times do I have to divide n by c to get to 1?

Examples:

  • Dividing is almost always log.
  • Finding an item in a sorted array using a binary search tree.
  • Finding a name in the phone book, open up half the book then determine if you have to check the first half or the second, then go to halfway between that half of the book, repeat.

Quadratic Time – O(n*n or n2)

The number of operations is proportional to the square of the problem size.

Examples:

  • Two nested for loops, usually
  • Any operation that multiplies two numbers by each other
  • Comparing two items as in a bubble sort or quick sort

Exponential Time – (Ocn)

The number of operations is proportional to some constant raised to the power of problem size. Any operation that would double the number of inputs. If the number of input grows, the time to complete the operation grows exponentially.

 

Determining Complexity

  1. Determine what variable(s) represent problem size (this is n)
  2. Write the number of operations in terms of n
    1. lines of code in series are added
    2. lines of code nested in other function calls or loops are multiplied
  3. Find leading term and drop coefficients (instead of 5n*n, then it’s n*n)
  4. If adding operations, choose the worst case (linear trumps constant, linear trumps logn, etc) and this is the overall time complexity.
  5. If multiplying, the time complexity is the product of both (n*logn = nlogn)

D3 Data Driven Documents

D3 is a JavaScript library which gives power to your front end by providing data to create and delete elements on the page, along with simple updating of that data and other elements on the page. The typical patterns for D3 are enter(), update and exit().remove() and a brief example of each is below.

To get started, you will have to find the element or class you want to do work on. If you are familiar with jQuery, then this should look similar (it’s similar to find()). You can start with the top element and dive into each child to find the one you want. Then you choose .select() or .selectAll(). If you are looking for a single element or the first element with that name use .select(), if you are looking for all the elements with that name use .selectAll(). If you look for a class instead of an element be sure to use the dot, .selectAll(“.trumpet”) or use a hash for IDs, .selectAll(‘#trumpet’).

Example:

// Initialize the page, join the data, then set a reference variable so there is less to type later.
var heightValues = [30,40,50];
var myPage = d3.select('body')
.data(heightValues, function(d) {return d;})

// ENTER() Since we have more data than elements on the DOM, we call .enter() and it adds div elements with a specified height from the data above to the DOM tree.
myPage.enter().append('div').attr('height', height)

// UPDATE Let’s update our height with random numbers now. No special function is needed for updating. Find the element or class using .select() or .selectAll() and then reassign the value of the .attr()
myPage.selectAll('div').attr('height', function(d) { return Math.random(); })

// Now if we wanted to delete an element we can remove an item from the data array
heightValues = [30,40];

// REMOVE() Then call .exit() with a .remove() and the element or class without data (the last div element) will be removed from the DOM. If we only called .exit(), the element would be left in the DOM with no data value.
myPage.exit().remove();

 

Class and Prototypes in JavaScript

Functional Class

Fundamentally, a function as a value on an object in JavaScript is called a method. Functional Classes in JavaScript are simply functions, which create a new object that contain methods and are donated by a capital first letter.

var Queue = function () {
var newObj = {};
newObj.method1 = function() {};
newObj.method2 = function() {};
return newObj;

};

Functional Shared Classes

Functional shared Classes will not contain their methods within the function in order for them to be used by other functions. An object is still created inside the function and returned. At the time the function is called and the object is created, the methods and their results are added to the object. If the methods change after this point, this object will not be updated.

  • Function creates and returns an object
  • Assignment of methods to object
  • Methods are copied at call time of the function
  • Use the keyword this in the methods to refer to the object that called it

var Queue = function () {
var newObj = {};
newObj.method1 = someMethod.method1;
newObj.method2 = someMethod.method2;
return newObj;
};

someMethod.method1 = function() {
this.count++;
return this.count
};
someMethod.method2 = function() {};

Prototypal

This is used in conjunction with the new keyword along with Object.create(obj).

The fact that the methods can be reused is very similar to functional shared, however, this creates a direct prototype link to the methods and the methods are used when the object created fails to find the property on it’s own object.

  • Must return an object in the function
  • A reference is created from the object to the methods via Object.create()
  • Methods are NOT copied at call time of the function
  • Methods are called at call time of the method
  • Use the keyword this in the methods to refer to the object that called it

var Queue = function () {
var newObj = Object.create(someMethod); // creates an object
return newObj;
};

var someMethod = {}; // create method object
someMethod.method1 = function() { // use prototype property
this.count++;
return this.count
};

someMethod.method2 = function() {};

var prototypeObj = new Queue(); // call new on the class

Pseudoclassical

The last one utilizes the built in property to all objects Object.prototype to store all of the methods on the object. This method does not require the creation of a new object, the assignment of the object to the methods (using Object.create) nor the return of that object inside the function class as JavaScript will do that for you. Again, the methods are called at call time and this is not a copy of the methods onto the object.

  • JavaScript creates and returns an object (magically)
  • The reference from the object to the methods is via the Object.prototype property
  • Methods are NOT copied at call time of the function
  • Methods are called at call time of the method
  • Use the keyword this in the methods to refer to the object

var Queue = function () {
var count = 0;
};

Queue.prototype.method1 = function() { // use prototype property
this.count++;
return this.count
};
Queue.prototype.method2 = function() {};

var prototypeObj = new Queue();

MEAN Stack – Front-End & Back-End Definition

The front-end (aka client-side, UI, UX, web) developer will rely on a back-end (server-side) developer to gather raw data from databases and process the raw data before ‘handing it off’ to the front-end developer to make it visually appealing on the user interface (UI) and interactive for the user experience (UX) . Typically, you’ll find sites with the front-end written in a different language than the back-end because most languages do not have capabilities to be both. Ruby, and Python are back-end languages and may use JavaScript as their front-end. JavaScript is special in that it can be both back-end and front-end.

The JavaScript MEAN stack requires front-end (AngularJS) and back-end (Node.js, Express, Mongo database) experience. Angular, Express and Node are frameworks of JavaScript, which means they extend the functionality of plain vanilla Javascript. Mongo is a database like SQL server or Oracle.

Building a REST API

Navigate to the repo location in terminal:

cd AutomationDatatools/distillery/

Start the server

DEBUG=distillery ./bin/www

Go to your web browser and navigate to the localhost

http://localhost:3000/api/imsreports

The structure looks like this for public, routes and views:

|– public
|   `– stylesheets
|       `– style.css
|– routes
|   |– api
|   |   |– imsreports.js
|   |   `– index.js
|   `– index.js
`– views
|– api
|   `– index.ejs
|– error.ejs
|– index.ejs
`– main.ejs

Code School Real Time Web with Node 5.3-5.4

This code will need some review. It works, but I want to understand the second objective more:

Now, use the name parameter from the URL to retrieve a quote from the quotes object and write it out to the response. Note: No piping here, just write the quote string to the response like you did in previous levels (and then close the response).

var express = require(‘express’);
var app = express();

var quotes = {
‘einstein’: ‘Life is like riding a bicycle. To keep your balance you must keep moving’,
‘berners-lee’: ‘The Web does not just connect machines, it connects people’,
‘crockford’: ‘The good thing about reinventing the wheel is that you can get a round one’,
‘hofstadter’: ‘Which statement seems more true: (1) I have a brain. (2) I am a brain.’
};

app.get(‘/quotes/:name’,function(req, res){
res.end(quotes[req.params.name]);
});

app.listen(8080);

Then the next one added on. Here’s the final code.

var express = require(‘express’);
var app = express();

var quotes = {
‘einstein’: ‘Life is like riding a bicycle. To keep your balance you must keep moving’,
‘berners-lee’: ‘The Web does not just connect machines, it connects people’,
‘crockford’: ‘The good thing about reinventing the wheel is that you can get a round one’,
‘hofstadter’: ‘Which statement seems more true: (1) I have a brain. (2) I am a brain.’
};

app.get(‘/quotes/:name’, function(req, res) {
var quote = quotes[req.params.name];
res.render(‘quote.ejs’, {
name: req.params.name,
quote: quote
});
});

app.listen(8080);

Code School Part 3 Exercise 1.13

This one stumped me for a bit. In scrum a fellow teammate said he’d offer some suggestions if I sent him my code.

This was my code prior to suggestions from teammate:

var applyAndEmpty = function(input, queue){
var amount = queue.length;
for (var i=0;i<amount.length;i++){
input = queue(input);
var removeFirst = queue.shift();
}
};

return applyAndEmpty(start, puzzlers);

This is my final code that worked in the exercise:

var puzzlers = [
function(a) { return 8 * a – 10; },
function(a) { return (a – 3) * (a – 3) * (a – 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
var start = 2;
var applyAndEmpty = function(input, queue){
var amount = queue.length;
for (var i=0;i<amount;i++){
input = queue.shift()(input);
}
return input;
};
alert(applyAndEmpty(start, puzzlers));

My teammate pointed out that I was calling .length twice. With the below statement, I was so close! They were not the right syntax and I was writing more complex statements than they had to be.

input = queue(input);
var removeFirst = queue.shift();

My code also had the applyAndEmpty as a return statement and it should have been an alert statement.

Puzzle Exercise Instructions

Now the people at Poplar Puzzles would like you to treat an array of functions like a Queue, passing the result of each function into the next until the Queue is empty. They’ve sent you the puzzlers Queue of functions, and the following instructions:

In a variable called applyAndEmpty, build and store a function that takes in an input number and a Queue of functions as parameters. Using a for loop, apply the Queue’s functions in order to the input number, where the results of each function become the next function’s input. Additionally, the Queue should be empty after the function is called. – PuZzLe MaSTeRs

Lastly, call the applyAndEmpty function using the provided start variable and the puzzlers Queue as arguments, and alert the result.

Error Message with incorrect code

Incorrect Submission: Make sure that you declare the applyAndEmpty variable properly.

 

More of my CodeSchool JavaScript Road Trip journey can be found on GitHub.

Code School JavaScript Road Trip Part 3

For a new project, I’m taking the Code School JavaScript trainings and I’m finding the stories and the problems to solve quite enjoyable as compared to Code Academy. It was smooth sailing until Road Trip Part 3, where my velocity slowed due to the complexity of the problem statements. I’ve realized that there are many ways to solve the problem and the way I’d solve them is not the point of the lesson, which is good because it’s teaching me new ways of looking at a problem.

My code, and thoughts on solving problems with CodeSchool Javascript Road Trip is logged in GitHub.