Kevin Ennis

Object.defineProperty for fun and profit

Mar 10, 2014

I ran into a weird problem at work last night where this one particular property of an object was undefined, but should have been a string.

What? Not that weird? Okay, fine.

But the weird part was that the object in question was getting created as the result of a call to JSON.parse(), and I knew that the JSON was totally valid. After a minute or two, it occurred to me that the value was probably getting set correctly when the object was intialized, but was then being overridden somehow elsewhere in the app.

So how do you find out where?


Here's the basic idea. We create a setter function on the object for the property name in question, and then just put in a debugger statement whenever the setter is called. That way, we can see the call stack in the console and figure out exactly where the assignment is happening.

Object.defineProperty(theObject, 'propName', {
  set: function() {

Totally simple. But somehow it had never ocurred to me until last night.

ES6 Promises Shim

Feb 17, 2014

This weekend, I had the brilliant idea that it might be fun to try to write a shim for ES6 Promises just by going through the spec and implementing it line-by-line.

Turns out, it was actually a really awesome learning experience -- and not really as hard as I thought it might be. The result is here on Github.

Writing to the spec was pretty enlightening. It's actually really well laid-out, and not as incomprehensible as I was expecting.

Here's an example: Promise.prototype.catch ( onRejected )

When the catch method is called with argument onRejected the following steps are taken:

Let promise be the this value.

Return the result of Invoke(promise, "then", (undefined, onRejected)).

Not so bad, right? It's pretty easy to see how that turns into code:

Promise.prototype.catch = function ( onRejected ) {
  return this.then(undefined, onRejected);

They're not all quite that simple, and you'll have to shim some of the abstract operations like SameValue() -- but overall, I was pretty surprised with how easy to read the spec actually is.

Anyway, I highly encourage people to try this out. I learned more this weekend that I have in probably the last 4 months.

Stereo to Mono With the Web Audio API

Aug 25, 2013

Ran into a situation yesterday where I needed to take the stereo stream from getUserMedia and mix it down to mono.

A quick Google search didn't turn anything up, so after I figured it out, I thought it might be cool to throw together a quick post in case anyone else ends up searching for the same thing.

var ac = new webkitAudioContext();

navigator.webkitGetUserMedia({audio: true}, success, failure);

function success( stream ) {
  var src = ac.createMediaStreamSource(stream),
    splitter = ac.createChannelSplitter(2),
    merger = ac.createChannelMerger(2);

function failure() {