It Ain’t Over Until the Fat Arrow Sings…

I know what you’re thinking: “What a terribly chosen blog title for SEO…”. At least, that’s what I thought when I first wrote it… //I digress

 

Anyways. I was soooo confused on understanding arrow functions. I didn’t even know they were defining functions! I wish Google did a better job at returning relevant results when searching for “javascript =>”.

I just wanted to reference this handy post by StrongLoop: “An Introduction to JavaScript ES6 Arrow Functions” (Now that’s a great SEO title…)

Arrow functions serve two main purposes:

  • more concise syntax
  • sharing lexical this with the parent scope

 

Here’s an example of how a function can be written using arrow notation:

function () { return 1; }
() => 1

I also appreciated the summary from that article:

It might be very tempting to just start using => instead of function everywhere. I’ve seen whole libraries written just using => and I don’t think it’s the right thing to do because of the special features that => introduces. I recommend using arrow functions only in places where you explicitly want to use the new features:

  • Single statement functions that immediately return (lambdas)
  • Functions that need to work with parent scope this

 

Intrigued? Read: “An Introduction to JavaScript ES6 Arrow Functions”

 

Read More

MongoDB: What is Normalized Data?

Alright! We’re on week 9 (out of 12) of our Orange County Code School bootcamp – four more weeks left! I’ve just wrapped up my 2nd project and will be doing a recap post about it soon. We’ve been learning about MongoDB and MongooseJS in class. Mongoose is an object modeling package for Node, and allows access to the MongoDB commands for CRUD (Create, Read, Update, Destroy).

I was doing some exercises, and came across two terms that I had no idea about: Normalized Data, and Embedded Data. Yeah, I know… what?

Here’s a quick recap from me reading of https://docs.mongodb.org/manual/core/data-model-design/

 

Normalized data models describe relationships using references between documents.

Basically, there are no embedded documents (the stuff between the curly {}), within another document. In the graphic below, you can see that the _id of the user connects all three documents (user, contact, access) together.

data-model-normalized

In general, normalized data models should be used when:

  • embedding results in duplication of data, but would not provide sufficient read performance advantages to outweigh the implications of the duplication.
  • to represent more complex many-to-many relationships.
  • to model large hierarchical data sets.

 

Embedded data models allow applications to store related pieces of information in the same database record. As a result, applications may need to issue fewer queries and updates to complete common operations.

Basically, there are embedded documents (the stuff between the curly {}), within another document. In the graphic below, you can see that there are additional documents (contact, access) included into the main document.

data-model-denormalized

In general, embedded data models should be used when:

 

Read More

Async Javascript with Promises

I’ve been struggling with understanding promises for a while but I found this video by Kyle Young really clear and helpful! I definitely recommend it to anyone also trying to better grasp the idea.

 

After watching the video, it made this article a lot easier to digest: http://www.html5rocks.com/en/tutorials/es6/promises/

This code from the above article sets up a nice Promise Pattern on the XMLHttpRequest

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {

    // Set up an XHR Object
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.onload = function() {

      // This is called even on 404 etc
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

 

This allows the XHR to be used in a really neat promise pattern:

get('story.json')
  .then(function(response) {
    console.log("Success!", response);
  })
  .catch(function(error) {
    console.log("Failed!", error);
});

Read More

Real Time with React.js and Socket.io

Update: Found these great articles on React.js. Wish I read them before I started my project! It would have made me feel a lot less depressed that I was taking such a long time to pick up the concepts of React!

ReactJS for Stupid People
Flux for Stupid People

 

As I briefly mentioned in my previous post, I was slightly too gung ho in choosing my second project: Twitterment. The idea behind Twitterment is that it’s an app that allows brands to view the Twitter sentiment around their brand keyword on a dashboard.

Problem 1: I was really attracted to the concept of having a real-time updating app, so that drew my attention to Twitter’s streaming API. I found out quite painfully though, that real-time I/O is not so simple to work with (at least, we didn’t learn about how to deal with real-time). Problems started to arise when I tried to make server-side AJAX requests to Twitter’s stream. I soon found out that once I send a server response from my Node server back to the client, I can’t keep pushing new Twitter stream data to the client.

Problem 2: I also tried to gather Twitter stream data into an array and send chunks to the client, but then I came across another performance issue where I was constantly repainting the DOM when I wanted to update the refreshed list of Twitter data. Yup, trouble.

So with a bit more research I realized that a possible solution to work with real-time stream data was to use Socket.io, and React.js could help solve some performance issues with frequent DOM updates.

It took me a painful 2 weeks to learn the basics of React.js and Socket.io, and refactor my app to implement both of these technologies. I say painful because I felt like I was making no ground for two weeks, while my classmates were hacking away – I had a couple of moments where I wanted to just trash the whole project and do something more straightforward!

 

Anyways. Drama aside – React.js and Socket.io is actually really interesting to work with, now that I’ve gotten a better idea of how these technologies work.

Socket.io essentially works by adding event listeners to an instance of my Express (Node) server, and adding a global socket variable that acts as an EventEmitter-like object on the client. So what I can do is attach a listener to trigger when certain events are emitted from my server (aka. run a function to update my list of Tweets on the client when the server receives new data from the Twitter stream!)

Even more cool is that both the server and client’s Socket object act as EventEmitters, so I can emit and listen for events in a bi-directionally (aka. If I can send a search keyword to the server, to track on Twitter’s stream). Beautiful! That takes care of sending and real-time data between my server and the client. Problem 1 solved. whew! =)

React.js is another library that provides a way to create interactive, stateful & reusable UI components. React uses a “Virtual DOM” that selectively renders nodes based upon state changes, while doing the minimal amount of DOM manipulation to keep my components up to date. Essentially, React uses a “diffing” algorithm to identify what has changed, and then goes through a process of “reconciliation” to update the actual DOM with the results of diff (aka. When I have new Tweet added to my array of Tweets, only the new Tweet will be rendered onto the DOM, instead of the whole list! Sounds exactly like what I need to solve Problem 2!).

 

Well, that’s the story so far. As you can see in the screenshot below, I’m still in the process of coding out this app, but the Twitter Stream is real-time and fully functional using React.js and Socket.io! Stay tuned or follow along on my GitHub repo: https://github.com/duncanleung/twitter-sentiment

twitterment-stream

Read More

Project 1 Recap: TravelGram

Okay, this post is over due, but it’s been really busy!

So my first project, dubbed ‘TravelGram’, has been a really fun experience (unlike my current second project, which is giving me sooo much grief, but that’s another story for another day… heh).

You can check out the GitHub repository here: https://github.com/duncanleung/travelgram

 

The idea behind TravelGram is that it’s a web app for travelers who want to explore a location before they go there. TravelGram allows users to search for a location around the world – Shanghai, for example, and the website will pull in geolocated pictures from Instagram.

The technologies that I incorporated to build out this project were:

  • Instagram API
  • Google Maps API and Places Library
  • AJAX
  • SASS and Jade
  • Bootstrap 3
  • A lot of beautiful CSS and Javascript animations (if I may say so myself =p)

TravelGram-1

Some of the cool features that I build out were:

  • Dropping marker pins where each individual picture was taken
    • This was done by creating an array and assigning each photo and marker an ID
    • An event listener for mouseover and mouseout is attached to both the marker and photo
  • Hovering over the picture highlights the respective map pin
  • Hovering over a marker on the map highlights the respective picture

Note: The filtering panel above the photos doesn’t work yet – I didn’t have time to finish that functionality, but the idea is there =)

TravelGram-4

The big success of this project is that it was only actually supposed to be a demonstration of the HTML/CSS front-end development skills that we had just finished learning in class. So the fact that I was able to pull in extra functionality with Instagram and Google APIs was really cool. I’m really pleased with everything that I was able to build out. Were were also only just starting to learn Javascript during the first week of the project, and so a lot of the functionality was built out through weekend research and side reading.

One of the main layout techniques that I was practicing in this project was CSS FlexBox. I found it to be a really powerful way to align and position components without the headache of thinking about floats and clearfixes. It requires a lot of prefixing to allow for cross-browser compatibility, but using an auto-prefixer helped with that =)

TravelGram-2

TravelGram-3

Some of my take-aways from this project:

  • Bootstrap is great for building out layouts quickly
  • Bootstrap can end up being really difficult to work with in fine-tuning layouts because of the way that rows and columns work. This article really helped to clear up some confusion: The Subtle Magic Behind Why The Bootstrap 3 Grid Works
  • Google APIs are pretty great to work with. Their autocomplete library implementation was literally just a couple lines of code to use
  • Instagram’s API is not so fun to work with. I was placed in a sandboxed as a new Instagram developer and had to send off a lot of request emails to friends to use their geolocated Instagram photos =)

 

I was also one of the 6 students selected (out of our class of 19) to present my project at the school’s Demo Day to some recruiters and CTOs in the Orange County area. Here’s a quick mug-shot that my wife got of me giving an intro to what we’ve been learning in class =)

IMG_1654

 

Read More

Random Weekend Javascript Musings: “for… in”

edit: Well what do you know; I was doing some light reading of Underscore.js’ documentation (yes, the things that I do in my free time…). But! I found out that Underscore.js has an Object Function to retrieve the names of it’s keys. Link.

_.keys({one: 1, two: 2, three: 3});
=> ["one", "two", "three"]

 

 

We’re getting into NodeJS concepts and exercises in class, and with that, we’ve been looking at JSON as a data format. ‘For loops’ are pretty standard examples in class to loop over the values in a Javascript object, and that’s when I had the random thought: “what if I want to get the name of the key? How do I do that?“.

Of course, that led to some research and I came across the for…. in loop. I’m pretty sure I’d learned it before in my codecademy or pre-OCCS prep work, but since it hasn’t been used so far in class, I decided to really dig into it. I really enjoyed this read: Exploring Javascript For-In Loops

Anyways, so here’s a method of getting access to the name of keys in an object:

for (var variable in objectExpression) {statement}

var myObj = {a: 1, b: 2, c: 3};
for (var property in myObj) {
console.log(property + ': ' + myObj[property]);
}
//console:
//a: 1
//b: 2
//c: 3

 

Be warned. Using for… in loops can cause prototype extensions of your objects to show up. I don’t wholly understand this concept since we haven’t learned about prototypes yet, but here’s a note nevertheless. Yes, more research lined up for me this afternoon =p

var arr = ['a','b','c'], indexes = [];
Array.prototype.each = function() {/*blah*/};
for (var index in arr) {
indexes.push(index);
}
indexes; //["0", "1", "2", "each"] whoops!

Read more on Exploring Javascript For-In Loops

Read More

Mental Check-In: Thoughts on Learning

A reaaaal quick post. I’m signed up to Travis Neilson’s emails (he does the DevTips channel on YouTube). Today he wrote some advice to a younger front-end developer.

“accept the criticism, and work hard to improve. This is a good time in your life, you are not expected to be the best, take advantage of that and make as many mistakes as you can, as long as you own them and learn from them.”

 

There are days in class when I’m just totally stressing out because I’m stuck on a concept and I can see in the corner of my eye that my classmates are whizzing past me. But it always helps when I take a water-break (I don’t do coffee anymore) and reset my mindset. The stress always comes from a nonexistent standard that I put on myself. I love the moments when I can reset, check-in the expectations, and remember that this is a time to be humble, and learn.

Well, time to run off to class!

Read More

More Git – Git Tutorial

Screen Shot 2015-12-06 at 4.34.47 PM

 

Git and more git. I sometime wonder if I’m spending too much time doing side reading on git, but I figure that since git is so commonly used in production that I ought to learn more than just the basics. I also recently read a Quora article: What are the characteristics of a bad software engineer that summarized that bad software engineers have: “A lack of empathy for other developers and the users of your code is a root cause for many symptoms of bad software engineering.”

I’ve also read/heard from other sources that good programmers should have clean and well documented code. Basically, no one wants to hire or work with a programmer who is going to write messy, un-maintainable code. Hence, all my side reading on how to build up a maintainable and clean git workflow.

Anyways… //endrant.

I found this really great Git tutorial hosted by Atlassian (the guys that made Jira – the project and software management system). Their tutorial organizes and breaks down the git commands and concepts into sections that seemed to match my needs of working with git:

  • Getting started working with git
    • Setting up repositories
    • Saving changes
    • Inspecting repositories
    • Viewing old commits
    • Undoing hanges
    • Rewriting history
  • Collaborating with remotes
    • Syncing
    • Pull requests
    • Using branches

Go check it out: Git Tutorial

Read More

Javascript Journey: document.querySelectorAll()

(Aside: I really should make a post about the first project that I’ve been working on… next time, haha)

So we’ve been journeying into Javascript for the past week-ish or so. We were interrupted by Thanksgiving break, but we’re back at it!

I’ve been implementing some fundamental methods that Javascript provides:

  • document.getElementById()
  • Element.addEventListener()
  • window.location.hash
  • Element.classList.remove()*
  • Element.classList.add()*
  • Element.querySelectorAll()

*classList.remove() and classList.add() is really handy sans jQuery, though it doesn’t have very good support on IE. Cest le vie…

 

What I want to chat about today is Element.querySelectorAll(). So apparently if you print out your selection console.log(Element.querySelectorAll()) you get what looks like an array. Great, seems straight forward enough.

But running Array.isArray(Element) on your element returns false. What? Well that explains why all solutions I’ve been looking up to traverse my ‘array’ has been coming up with some variation of the below to traverse the ‘array’:

var divs = document.querySelectorAll('a');
  [].forEach.call(divs, function(div) {
    // do something;
  });

Turns out that what document.querySelectorAll returns is actually a NodeList, and what [].forEach.call(divs... ) is doing is creating an empty array, and using the array’s prototype method through Javascript’s .call() to allow the NodeList to take advantage for the the array’s .forEach() method.

This seems a bit messy, but I guess it’s the solution I have for now!

Until next time =)

Read More

Git With It – Version Control Best Practices

It’s a lazy Saturday afternoon before Thanksgiving and I’m reading about Version Control Best Practices, thrilling, right? But in all seriousness, I’ve realized both how vital and helpful, yet confusing, version control can be for a project.

We’ve been working on our first project for about a week (I think? Time sort of flies while doing this bootcamp). I’m really itching to continue development, but I feel the need to take a step back and really dive deep into the recommended workflow for Git before continuing.

I’ve been using the basics of Git staging and committing enough to run into situations where I’d like to read up a bit more on some advanced best practices – especially regarding using branches to build out new features or fix bugs. So far, we’ve only just been working mainly in the master branch (at least I have been =p).

Some points that should be ‘common sense,’ yet that I’ve found helpful are:

  • Use present tense for for commit messages to be consistent with generated messages from commands like git merge
  • Commits should be a wrapper for related changes – two separate fixes should be two separate changes
  • The better and more carefully crafted the commits, the more useful version control will be
  • Good commit messages should answer two questions:
    • What was the motivation for the change?
    • How does it differ from the previous version?
  • Test before committing!
  • Don’t commit half-done work. Use git stash to save unfinished work

Read More