Category Archives: JavaScript

An Itsy-Bitsy, Teeny-Weeny, Yellow Polka Dot … EventEmitter!

I recently attended the M’s workshop on functional programming, in which I learned that I needed HELP. (M is a fantastic facilitator at Hacker School. Here is the link to the blog post she wrote about said functional programming workshop.) I knew my client-side code was a mess, but I was clueless as to why exactly it was so stinky and at a total loss about how to fix it. Her workshop simplified the concepts behind functional programming, and made it approachable, and (more importantly), applicable. I’m writing this post as a summary of what I learned and how I’ve recently started applying it.

First off, here are some of the tips and tricks I took away from this afternoon of functional programming examples:

Declare It!

Write DECLARATIVE code, not IMPERATIVE code. Her example was writing a function called “make-me-a-sandwich” versus writing some code that is a tedious list of the steps necessary make a sandwich. In examining my recent code in this light, I found it full of tiny instructions that give the reader no overall sense of where it’s going and why. Plenty of room to chunk that shit up into declarative functions!

Avoid Mutating

Write functions that RETURN stuff without mutating what they are given. Functional functions take some parameters (say an array or string or object), use what’s within them (no referencing outside [especially not GLOBAL!] variables), and neatly return a modified COPY of what they were given. This is great, as you never end up writing over something you needed or modifying an outside variable unintentionally. Also, if you constantly return a clean copy of your starting data, it’s far easier to chain series of small tasks together, which makes it clear to the reader what you are doing with your code.

Quit Iterating with For Loops

I.E. Use MAP, REDUCE, and FILTER. These functions are great! I had little experience using them, but they save you a bunch of hassle and make it very clear to the reader what you are doing and why. M’s great example of all the unrelated crap people throw into a for loop made me laugh at myself out loud (new acronym: LAMOL?). I do that all the time! I used to think I was being efficient, getting more done in one loop. But it’s far cleaner to map my change onto my array of items, and it returns me a new, safe copy. I have questions about the potential Big O sacrifice in mapping over my data many times instead of doing a bunch of crap in a for loop all at once, but for my general purposes (handling a very small amount of data — generally loops under 20 items), the benefit in clarity certainly outweighs the loss in performance.

Applying My New Knowledge to My Own Code

As always, much harder than expected. After M’s workshop I knew vaguely what had to be done, but in my client-side code, I have functions that handle JSON requests and responses, and functions that handle resultant DOM manipulation, and they must work together so intricately that I found myself with a mess of delicately interwoven spaghetti code. Appetizing, sure, but not pleasant to pick apart, and definitely not easy to make changes to.

After puzzling at the mess for an afternoon and evening, I sought M’s advice. She recommended implementing my own tiny client-side Event Emitting system so that my server-communication code could alert my DOM-manipulation code to changes without being dangerously interlaced. “Brilliant!” I thought. “Terrifying,” I thought. Implement my own Event Listener and Emitter?!? Are you crazy? Luckily, M showed me some example code, and demystified such a seemingly complex idea significantly. So, drumroll please, here it is in the flesh, my Itsy-Bitsy, Teeny-Weeny, Yellow Polka Dot Event Emitter:

var EventEmitter = function () {
    this.handlers = {}; 
    // we need to keep track of what actions (functions) are mapped to which named events

EventEmitter.prototype = {
    bind : function (event, fxn) { 
    // this is how we add "listeners" to certain events
	this.handlers[event] = this.handlers[event] || []; 
        // make sure we have an array in our handler, mapped to our event, to push our function into
        // add our function to our event's array of functions
    emit : function (event, data) {
	if (this.handlers[event] !== []) { 
        // if this event has listeners bound to it
	    this.handlers[event].forEach(function(fxn) { 
            // for each of our functions mapped to our event
                // do the function on the data we emitted
	    }, data); 
            // forEach takes the parameter to pass the inner functions last

var sayMessage = function (message) { 
// let's define a test function that takes a piece of data

var emitter = new EventEmitter(); 
// instantiate a new EventEmitter

emitter.bind('open', sayMessage); 
// bind the sayMessage function to the event called "open". 
// this gets stored in our emitter's "handler" map.

// let's emit an event called "open" with the data, "banana", and see what happens:

// => if you put all this in a window.onload() function and load it in your browser, it will alert "banana"!

Okay, so what’s cool about this, and how does it relate to functional programming? First off, it’s cool because now my server-message sending and delivering code can be completely separated from my DOM-manipulation code. This is important. These two chunks of code deal with completely different things, and we want to keep them in their own zones. Then we can make changes within them without worrying about fudging up the other. (For the non-technical, DOM stands for Document Object Model, which is some garbage way of saying my HTML or the text-y output and physical elements on my webpage that the user sees, in opposition to the pure data that is transferred to and from the server.)

Anyway, what was exciting about writing this bit of code was the function forEach(). I had not used that before, and my (NEW) instinct was to try to map my array of functions to my bit of data (though usually map works the other way — mapping a function to an array of data…). Thankfully, M recommended forEach(). Upon researching forEach(), I found that it takes this second argument, which the documentation defines as “the object to use as this when executing callback.”

What’s exciting is that several weeks ago I doubt I would have understood that. Now, and especially after talking about closures in the functional programming workshop, I understand much better: that parameter is defining the runtime object or data that the function(s) you are calling within your forEach loop will be applied to. This is what allows us to “emit” an event and include with it some data that is (not magically!) passed to the function(s) that are mapped to that event in our handler map. Those functions, thanks to forEach(), are able to access that data we passed with our event emission. In my example, it means my event emission code can attach whatever it wants, and through the map inside my event emitter and the forEach execution, my bound function (in this case called sayMessage) can access the data I want to give it (in this case “banana”). Amazing!

Hacker School Day 10: About TCP/IP & a Node.js Hello World

.Where. .to. .begin. .?.

I began today slightly bored of Nefario Teaches Typing. There’s a WHOLE lot more I could do with it, but I won’t learn anymore by doing those things. I mean, sure, I’d get a little faster at some simple stuff, but I’m ready to be CHALLENGED, PUZZLED, PERPLEXED. So I put that on the shelf for now (I think I’ll still work on it in the evenings, as a little side-project) and sought some facilitator advices. M suggested that I either delve into a meaty client-side project such as a drum music simulator thing or that I try to write my own super-simple, crappy web server. Since I know little (NOTHING) of sockets and such, I figured that’d be a worthy pursuit. I proceeded to spend the rest of today reading up on Node.js, packets, sockets, TCP/IP, and other bizarre terms. From this, I think I’ve extracted a bit of knowledge. Please see below:


The what? TCP stands for Transmission Control Protocol. That means nothing. What they should call it is: Reliable Communication Command Center, the RCCC. Because that’s what it does. TCP is a protocol (read: set of rules or instructions) for sending and receiving lil’ packets of info between and within computers. [NOTE: feel free to well-actually me in the comments: I won’t be offended, I’ll merely learn better.] Okay, so, from what I understand, TCP works with the IP (Internet Protocol, another set of instructions) to coordinate communication between computers in packet-switched networks.
“What’s a packet-switched network?” I’m glad you asked! It’s when things (computers in this case) transfer data in little packets instead of via a constant bit stream. This means: you can send some data then stop, then send more; the packets can travel via different routes to get to the same place; you can check for errors in delivery, and you can grab data from multiple hosts (computers serving up data). Packets are great! Let’s talk more about what a packet actually is:


Packets are like datagrams, but not quite. Datagrams are little chunks of data, packed light for travel. Datagrams contain some header info about where they’ve come from and where they’re headed and what type of data they contain, then they have some sort of body of data, called the data payload. I picture this as a Chinese Dragon head that barfs up addresses and types, stuck to a dump-truck of solid gold data bars. (It’s been a long day.) The thing about datagrams is they don’t pay attention to their own survival. They contain no way to tell whether they’ve reached their final destination, and no data about error-checking for their missing friends or limbs. No guarantees! Sent then forgotten. Packets, on the other hand, are souped-up dragon-trucks: in addition to the basic datagram info, packets also contain info about which of them belong together and in what order, and they (somehow) have ways to instruct their receiver about how to test them for errors (I think this has to do with some magical size computation that would detect missing data).

IP Addresses

This is just cool. You know how when you get your IP address it just seems like a bunch of numbers? Well, it is, but there is a little logic to it. Everything in the header of these packets has a specified (by the protocol) amount of data it can take up, which I imagine makes it easier to parse and such. The amount allotted for an IP address is 4 bytes (each 8 bits long), which means the “address” is 4 “numbers” long, each separated by a period, each between 0 and 255 (which are all the numbers you can make with 8 bits: 00000000 – 11111111), hence something like Cool, huh? I thought so. Also, IP addresses are the personal address of your computer. Something like that.


Today I read a bunch about node and learned how to write the teeniest web server. Here it is:

// require the http module in node:
var http = require('http');

// write a listener function that will do something (send a response, ideally) when the server receives a request:
var webListener = function (request, response) {
    if (request.method == 'GET') { // what to do if this is a GET request (most are!)
        console.log("Request was a GET"); // just tell the terminal that it was a get request for now
        console.log("URL: " + request.url); // tell me that url, please!
    response.writeHead (
        200, // that code means the request was successful, tell the client "200, yay!"
        { 'Content-Type' : 'text-plain' } // We're going to send back some plain ol' text
    response.end('Hello World!'); // end our response with the data (text) that we want to send back

// make a new instance of the server object and pass it our fancy listener function from above
var server = new http.createServer(webListener);

// tell the server to listen up! (and give it a port number to listen on and a host to use -- localhost)
server.listen(8124, "");

// tell me you're working, server!
console.log("Server running at");

Oh right, first install node (use homebrew!). Then put the above code in a file, and call it example.js. Save it somewhere, navigate to that place in Terminal (someday I’ll write a super-teeny Terminal intro), then type “node example.js”. BAM! Web server, up n’ runnin’.
Phew! That’s it. I’ll go into more detail tomorrow about what the particulars of each of these are, but in general, the client (your computer) connects to a host (now my computer) and they say “coo’, let’s talk.” So your client computer requests something from mine (you want to see my website, of course) at the address that is my computer, connected to the port that my server is listening to. My server gets that request and responds however I tell it to (in this case by sending you back “Hello World!”). Tomorrow’s goal: send back an html file. I guessed that I would have to read a file’s content into some sort of buffer and send it appended to a packet, and I think I’m right. I haven’t yet looked too far into the details of that, but I’ve got a general idea of how it’ll work.

Stay tuned, folks! And thanks for reading.

FORGOT! Here’s my illustrated understanding of TCP and IP:photo

Hacker School Day 9: SICP review, Sinatra solutions, JS productivity

I dabbled in too much today! But I think it’s okay. Just for today.

First up, I want to write about SICP*, and what I reviewed today. Hopefully that will help cement these complex thoughts a little more firmly into my malleable medium of brain. I started working through SICP again with another (SLOWER) group. This is more to my liking, as I merely want this to be an enlightening side-project.

SICP Exercise 1.5

(define (p) (p))

(define (test x y)
    (if (= x 0)

Evaluate (test 0 (p))
This exercise tries to demonstrate the difference between Applicative-Order Evaluation and Normal-Order Evaluation. Let me try to explain: in Applicative-Order Evaluation (which is similar to how the Scheme interpreter actually evaluates code), you evaluate the parameters of the function or expression FIRST, then plug your results into the outer function(s). In Normal-Order Evaluation, you leave your parameters as junk-words and expand out the outer functions as much as possible. In fact, you expand everything down to simple operations as much as possible, THEN you go through and evaluate it all back up and simplify. So, in the case of the code above, approaching it Applicatively, we would FIRST evaluate 0 and (p) (since these are our parameters to the test function). When we try to evaluate (p), we are returned the function (p), which then returns the function (p), which then returns the function (p), etc. The program runs forever, just trying to get some real stuff to put into the parameters of test. Yikes! When we approach this Normally (ha! except not really — please note my use of capital “N”), we first expand out our function: (if (= 0 0) 0 [STOP!]. With if, since it’s a special form and not a normal procedure, we don’t plug everything in everywhere up front; we instead plug in our first test case and evaluate it, then either evaluate the success expression or evaluate the else expression. In this case, we get to (= 0 0) (does 0 equal 0? why, yes, it does!) and we return 0. Done. Easy. No infinite loop.

SICP Exercise 1.6

In this exercise, Alyssa P. Hacker and her friend Eva Lu Ator (author’s names, not mine) decide that if is just a sub-set of cond (conditional), where there is only one test case, so they decide to write their own if function based on cond:

(define (new-if predicate then-clause else-clause)
    (cond (predicate then-clause)
    (else else-clause)))

This works fine if you’re just evaluating a few simple numbers, but if you use it for a process involving iteration, it may cause an endless loop. Here’s why: (SICP example slightly simplified)
Let’s write a function called improve guess where we say “if (guess is good enough) (return guess) else (improve guess),” and improve guess calls itself. If we use the normal special form if as defined by Scheme (or any language, really), the interpreter knows to only look at the else clause IF the first clause is false. Fine. Great. What’s the big deal? If we instead use our homemade function new-if, we have to plug in: (new-if: (good enough?) (guess) (improve guess)) into our function. As I talked about above, if we were to evaluate this Applicatively, similar to the way the Scheme interpreter does, we would FIRST evaluate our parameters before doing the outer function stuff, which means we would FIRST evaluate the parameter “improve guess” which means we would call our function all over, plug in the same parameters, evaluate them (which would mean evaluating “improve guess”, which would mean calling our function yet again, plugging in the parameters, evaluating them (which would mean …)). And if you run this code in the Dr Racket interpreter (in which I declare the language to be Scheme), it only quits when it’s run out of its allotted memory. Ha! SO. THAT is why some functions are built-in to languages with SPECIAL instructions, such as IF, AND, OR. Take that, Alyssa P. Hacker and Eva Lu Ator! I guess that’s whatcha get for tryin’ tah be clever.


Not Frank. The other one. Less dancy, unfortunately. This one is a light-weight Ruby web server (I think). Anyway, I used it for my tiny gmail filter maker about a month ago, so when a classmate was struggling with it I offered to lend an eye. While we didn’t make leaps and bounds of progress, it challenged us both to think about harder about GETs and POSTs and how to see what of our parameters were getting properly delivered. Ultimately, I think she’ll need to switch to session variables, which I would love to learn how to do with Ruby and Sinatra, but I also had to get back to work on:

Nefario Teaches Typing

… my typing game. Progress so far: added the beginnings of a keyboard, changed the frame rate of the character’s animation, added scoring, added pause and resume. Next up: do more with the keyboard, pull some of the html-building out of the JavaScript and let it just be already in the html the way I want (will try to do this as a new “branch” so that I can go back to it… that will be an experiment/learning opportunity with git). I also need to refine the “rules” so that the level can be won or lost and is somewhat tailored to the player’s typing speed and accuracy. So much to do!

*SICP = Structure and Interpretation of Computer Programs, a fundamental work about what it means to write programs, used at MIT, “changed my life,” blah, blah, blah. It’s actually pretty cool, though quite dense.

Hacker School Day 8.Friday: On which I “implemented” a “stack” in JavaScript!


This afternoon, in a matter of just a few hours, I learned:

  • What is meant by a “stack”: a data structure in which you pile things on top, much like books. These are not meant for accessing data from the earliest elements — they are intended for pushing (adding items to the top) and popping (taking items off the top).
  • What it means to “implement” your own “__________” (in this case a stack): build your own version of the thing, ideally using fewer built-in functions or structures than would be handy. (See below for an example.)
  • What a “linked list” is: (sorta) A data structure in which you store each element and it’s “pointer” to the element before it. This means in order to get from element “a” at the beginning of a stack, to element “f” that you’ve stacked up to now, you’ve got to go from “f” to “e”, then from “e” to “d”, etc., until you get back to “a”. Not sure what situations this would be super-helpful for (same way I feel about a stack), but I guess it’s good if you only need the most recent few elements? (Comments, enlightenment, and such are most welcome!)
  • Node is easy to install with homebrew: literally (first remember to update and doctor your brew):
    ~$ brew update
    ~$ brew doctor
    ~$ brew install node

    DONE! Now I can run js files in the terminal!

On “Implementing” a “Stack”:

Okay, so in JavaScript (as in most higher-level programming languages), there are built-in tools that do the stack-y things you need to do already, so a Super Cheaty Implementation of a stack in JS might be something like this:

function CheatingStack () {
	this.contents = [];
CheatingStack.prototype.push = function (item) {
CheatingStack.prototype.pop = function () {
	return this.contents.pop();
CheatingStack.prototype.isEmpty = function () {
	return (this.contents.length === 0);

That makes use of built in methods push() and pop(), which put an item on and pop an item off the stack, respectively.

That sort of implementation is neither challenging nor interesting, so naturally I had to try harder. The facilitator, AO, who was helping me with this hinted that soon in SICP (the fundamental book of computer programming that I’m reading), the author will break all data down into pairs, and he showed me how pairs could just be “implemented” in JavaScript as an object with two parameters and two properties. From there, with some on-paper reasoning help from my lovely fellow student RS, I figured it out! I then tested it using console.log(), but I would like to implement more unit-testing methods that AO demonstrated. The trick (for the non-technical readers that I someday hope to have) is to create a tiny “Item” object that merely stores a value and a “pointer” (in this case, the item that comes before it). Then in your stack when you push a new element in, you make a new “item” object for it containing itself as the value and the last head object of your list as what it points to. All you have to track in your “stack” is what object you are currently pointing to. Then when you want to pop an item off the top of your list, you grab that head object, and fetch from inside it the object it’s set to point to and make that your new head. In my initial round of code, I was also storing an extra property called “prev” in my stack, but another facilitator, AK, kindly showed me that was entirely unnecessary! (Another great reason to show someone your code immediately.) For the technically inclined and curious, here’s a link to the code: Implementation of a Stack in JavaScript (gist).