Common ES6 Mistakes

const myObject = {
  emails: null
}

const { emails = [], users = [] } = myObject;

console.log(users.length);   // users is undefined (defaults to []) This returns 0.
console.log(emails.length);  // this will bork; you can't get length of null.

Strings are iterables

const set = new Set('555')
console.log(set);   // {'5'}

More to come as I continue to make more mistakes…

A Byte of JS

A conversation with a co-worker…

So, to answer your question: how do you represent the character J…
Open up dev tools and type 'J'.charCodeAt(0)
It will return 74.

Why does 74 represent J?
According to charCodeAt, the first 128 codes match up with ASCII table. So it takes 7 bits (27 = 128) to represent everything on the ASCII table, letters, numbers, common symbols, and other important ‘characters’ such as space, tab, line-feed and carriage return.

7 bits, or 7 0’s and 1’s….

What does 74 translate to in bits in RAM or on disk?
Or, how do you go from decimal to binary?

Whats the largest power of 2 that is less than 74? 64, or 26.
Take the remainder, (74 – 64 = 10), whats the largest power of 2 that is less than 10? 8, or 23.
Take the remainder (10 – 8 = 2), which is 21.

So 74 = 26 + 23 + 21 = 64 + 8 + 2
Since the right-most digit of a binary number corresponds to 20,
the 2nd from the right corresponds to 21,
4th from the right corresponds to 23, and
7th from the right corresponds to 26.
(Think of it as a zero-indexed array starting from the right).

27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
0 1 0 0 1 0 1 0

So the 7 bits used to represent the letter J on disk are 01001010.

All this talk about bits, whats a byte?
A byte is 8 bits. So one byte of computer space can represent up to 28 (256) characters. In JavaScript, thats the first 128 on the ASCII table, then another 128 of other special characters.

If J can be represented by one byte, then 1 kb = 1024 bytes, or 1024 of the letter J.
Why 1024? Because computer scientists think in terms of binary, and 2^10 = 1024.
Then whats a MB? 2^20, or 1024^2, or 1,048,567 instances of the letter J.
But this is all assuming characters are 1 byte….

Are all JS characters 1 byte?
No, JS characters can be 1-4 bytes long. Special characters will take up more than 1-byte, and this is where you can get nasty bugs with JS if you’re not aware.

The docs for charCodeAt say that it returns values 65535 or less. Thats 216, or 2 bytes.

So what about characters that are 4-bytes long?
They’re represented by surrogate char codes, two char codes joined together to represent a char.

Try: '𐐷'.charCodeAt(0)
'𐐷'.charCodeAt(1)

You’ll get two separate char codes!

Who cares? How does this lead to bugs?
You can’t always rely on String.prototype.length to return the number of characters in a string. Suppose you are validating the length of a string, how should you handle special characters? Because:
”.length

Will return a value of 2.

This is boring, can you end with a joke?
Sure. There are 10 types of people in this world: those who understand binary, and those who don’t.

My Fiancée’s Wedding Shoes

As the wedding date approaches, I will probably be blogging more about the wedding and less about programming.

My fiancée’s wedding shoes just arrived, and I might be more excited about them than she is.

Custom Glitter Christian Louboutin Wedding Shoes

Custom Glitter Christian Louboutin Wedding Shoes

We ordered them a few weeks ago from the Christian Louboutin in San Francisco. She wanted strappy shoes that were sold out, but we were able to place a custom order. We we’re able to get the style that she wanted, in the exact color that she wanted.

Custom Cinderella-Inspired Glitter Christian Louboutin

Custom Cinderella-Inspired Glitter Christian Louboutin

We were told that brides-to-be had the option of getting blue insoles, which turned out to be a great idea. The soles show through the PVC sides; in addition to the glitter, it really drives home the “Cinderella” feeling. A step up from the glitter would’ve been the Swarovski crystals, but that would’ve more than doubled the price of the shoes.

What I really appreciate is the attention to detail. The sides of the soles are all glitter, so it looks like she is tip-toeing on crystals when she slips the shoes on. And finally, the soles have a unique horseshoe design at the heel — again, all glittered up.

Glitter Christian Louboutin

Glittery Soles

If you are looking for a “low-budget” alternative to designer Cinderella-inspired shoes, these definitely deserve consideration.

Quirky Behavior with Array.prototype.Reduce

I ran into this issue with reduce when I tried to flatten an object containing arrays.

var myObj = {
  "HomePage": [
    "ModuleA",
    "ModuleB",
    "ModuleC"
  ],
  "ProfilePage": [
    "ModuleB",
    "ModuleC",
    "ModuleD"
  ]
};

My initial approach was to reduce everything with the following:

Object.keys(myObj).reduce(function(a,b) {
  return myObj[a].concat(myObj[b])
});

This works, but will run into an error when your configuration object only has one key. It’s as if reduce is not called when the array it is operating on has fewer than two elements.

var smallObj = {
  "HomePage": [
    "ModuleA",
    "ModuleB",
    "ModuleC"
  ]
};

Object.keys(smallObj).reduce(function(a,b) {
    console.log('reducing...');
    return smallObj[a].concat(smallObj[b])
})

If you try to add an initial value of [], it will throw a TypeError: Cannot read property 'concat' of undefined.

Object.keys(smallObj).reduce(function(a,b) {
        return smallObj[a].concat(smallObj[b])
}, []);

Alternative Solution

Suggested by @rouxbot:

Object.keys(smallObj).map(function(key){return smallObj[key]}).reduce(function(a,b) {
  return a.concat(b);
})

Measuring First Paint Time in Chrome

One handy metric that WebPageTest captures is the first paint time. Unfortunately, WPT uses binary code that is injected into the browser process.

A close approximation is available in Chrome called window.chrome.loadTimes(), which returns the following object:

{
  connectionInfo: "http/1",
  finishDocumentLoadTime: 1422412260.278667,
  finishLoadTime: 1422412261.083637,
  firstPaintAfterLoadTime: 1422412261.094726,
  firstPaintTime: 1422412258.085214,
  navigationType: "Reload",
  npnNegotiatedProtocol: "unknown",
  requestTime: 0,
  startLoadTime: 1422412256.920803,
  wasAlternateProtocolAvailable: false,
  wasFetchedViaSpdy: false,
  wasNpnNegotiated: false
}

The firstPaintTime property is measured in seconds since epoch with microsecond resolution.

We can combine that with window.performance.timing.navigationStart, which is measured in milliseconds since epoch:

window.chrome.loadTimes().firstPaintTime * 1000 -
  window.performance.timing.navigationStart

This yields the time (in milliseconds) since navigation starts before first paint event occurs.

Cross-Browser First Paint Telemtry

Some code for cross-browser firstPaint time measurements: https://github.com/axemclion/karma-telemetry/blob/master/src/scripts/benchmarks.js

Iterating Over Object Values

JavaScript allows us to iterate over objects and arrays with for...in, but it only provides access to the object’s keys, not values.

var myArray = ['x', 'y', 'z'];
for(key in myArray) {
    console.log(key);
} //=> 0, 1, 2

If you wanted to access the values, you’d have to access it manually:

for(key in myArray) {
    console.log(myArray[key]);
} //=> x, y, z

Practically, if you wanted to iterate over an array, you might use the forEach method, which gives you access to the key, value, as well as entire array:

myArray.forEach(function(value, key, array){
    console.log(value);
});  //=> x, y, z

For…Of Loops

ES6 allows iteration over array values with for...of loops:

var myArray = ['x', 'y', 'z'];

for(key in myArray) {
    console.log(key);
} //=> 0, 1, 2

for(element of myArray) {
    console.log(element);
} //=> x, y, z

Iterating over Objects

What if you wanted to iterate over an object? In ES5, you could use forEach on Object.keys():

var myObj = {
    'a': 'foo',
    'b': 'bar',
    'c': 'baz'
}

Object.keys(myObj).forEach(function(v, k, a){
    console.log(v); //=> a... b... c...
    console.log(k); //=> 0... 1... 2
});

for...in loops also work on objects, but similar to iterating over arrays you only have direct access to the key, not value:

var myObj = {
    'a': 'foo',
    'b': 'bar',
    'c': 'baz'
}

for(key in myObj) {
    console.log(key);
} //=> a, b, c

For…of and Object Iterators

Out of the box, for...of loops don’t work with non-array objects. That’s because the for…of loops relies on an internal iterator, something that comes for free with arrays.

If you’d like to use for...of to iterate over an object’s values, you can do so after defining it’s iterator.

Making a Jewelry Box

When I was thinking about preparing the jewelry gifts for my fiance, I encountered a unique problem: there was a traditional Vietnamese necklace called a kien – a solid loop of gold ten inches in diameter. We had a set of three made in Viet Nam, but we needed a way to present the gifts at the ceremony.

Vietnamese áo dài and jewelry (Kien)

Vietnamese áo dài and jewelry (Kien)

Calligraffiti

I couldn’t find a jewelry box that was ten inches in diameter, so I thought it’d be nice to customize a special jewelry box. I wanted to personalize it by engraving her initials on the lid. I had envisioned something scripty with a lot of swashes, but street art influences found their way into the final sketches.

Initial sketch of... initials.

Initial sketch of… initials.

I started with a wooden box at Michaels. I transferred my sketch to the box, then used a woodburner to make it permanent.

Initials sketched onto Jewelry Box

Initials sketched onto Jewelry Box

I started with the Universal point for the outline. Once the outline was complete, I used a shader tip for the inside.

Initials woodburned onto Stained Jewelry Box

Initials woodburned onto Stained Jewelry Box

Inside the Jewelry Box

The inside of the box is divided into two sides: one, tilted to mount the kien; the other, divided into ring rows.

Custom Jewelry Box (Inside)

The Inside of the Jewelry Box

Making Ring Rows

For this I used:

  • 1 sq yd Red Microsuede – You’d think felt would cut it, but it looks like crap. Considering how much time you will invest in making this box, splurge a little bit and get a nicer fabric.
  • Foam Board – this will form the structure of the insides of the jewelry box
  • Medium Density Foam Core – fabric store
  • Foam (optional) – stiffer than foam core, more flexible than foam board
  • Woodburning Iron, Blade Tip – this is used to score the foam board, and a heated blade will melt through the foam core
  • Spray Adhesive – to wrap microsuede around the foam core

I used foam board to give structure to the insides and serve as the divider. The “soft” parts, such as the ring rows, are foam core wrapped in micro-suede.

Đám Hỏi – A Vietnamese Engagement Ceremony

My fiancée and I decided to have a traditional Vietnamese engagement ceremony so that our parents could get a chance to meet. We wanted to host a ceremony that faithfully captures the essence of Vietnamese traditions, and infuse it with elements of Christianity. The thing is: neither of us are very traditional, so preparing for this event meant doing lots of research! Hopefully this will help couples plan their event in the future.

The Procession

It begins with the groom and his family making their way over to the bride’s house. Men from the groom’s side each carry a tray, called mâm quả. Traditionally, there are an even number of trays, a roasted pig, and a tea set.

Engagement Ceremony Entourage

Engagement Ceremony Entourage

The groom’s parents knock on the door, and a representative from the bride’s family greets them, and tells the groom’s family to wait while the bride gets ready.

Vietnamese Bride Waiting

The bride, patiently waiting

My little brother led off the line-up with the tea set. The rest of the gifts are in trays, 16-inches in diameter. Gifts can include:

  • Betel and Areca – trầu cau, symbolic of marriage in Vietnamese culture
  • Tea
  • Champagne
  • Fruit – this is usually the heaviest!
  • Sticky Rice
  • Cakes

The bridesmaids line up outside of the house and accept the gifts from the groom’s family.

Engagement Ceremony Gift Exchange

Engagement Ceremony Gift Exchange

The Ceremony

The bridesmaids bring the gift inside so that the groom’s family (in my case, my mother) presents them to the bride’s family.

Engagement Ceremony Gifts

Engagement Ceremony Gifts

The next part is the family introductions: a representative from each family introduces the members of their respective families. Once introductions are done, the bride is brought in to meet her new in-laws.

Since our two families are Christian, we invited our pastor to share a few encouraging words.

Next, my mother presented the bride-to-be with jewelry. Traditionally, the bride is given a pair of earrings and an engagement ring. In our case, we commissioned some pieces to be made in Vietnam – specifically the three gold necklaces.

Engagement Ceremony Jewelry Set

Engagement Ceremony Jewelry Set

We concluded the ceremonial portion by serving tea to our parents.

Vietnamese Tea Ceremony

Vietnamese Tea Ceremony

Afterwards, guests were invited to stay for a small meal. We had family members helping out non-stop in the kitchen!

Dam Hoi Food

Dam Hoi Food

At the end of the ceremony, the bride’s takes half of the gifts (that’s why you bring two of everything!) and gives it back to the groom’s family.

The Outfits

To finish up, here’s a close-up of my fiancee’s outfit: a modern take on the traditional áo dài.

Vietnamese female áo dài

Vietnamese female áo dài

… and a happy-couple picture!

Traditional Vietnamese áo dài

Traditional Vietnamese “áo dài”

Getting Started with Ember.js: The Missing To-Dos Manual 2.0

Ember.js is a lightweight JavaScript framework that packs a heavy punch when it comes to binding data between objects and making the appropriate updates to the view template. As websites continue to trend towards using CSS and JavaScript to create rich interactions (sans Flash) and more of the business logic shifts to the client side, this framework helps alleviate a lot of the tedious scripting.

I first heard of Ember.js when I was exploring SproutCore, which was on version 1.6 (released in June 2011). SproutCore 2.0 was announced in May 2011, but was later renamed Ember.js (which is currently on version 0.9.7.1), while SproutCore recently came out with version 1.8 in March 2012.

SproutCore 1.6 featured excellent documentation that showed how to create a To-Do list quickly. I couldn’t find a comparable tutorial for Ember.js, so I figured I’d write my own.

Continue reading