For those of you who don’t know me: I’m a huge Shakespeare geek. I love performing, reading, and teaching Shakespeare. I especially love his First Folio, the earliest surviving publications of his work. The problem? Weird typography. At the time it wasn’t unusual to switch v’s and u’s and i’s and j’s around willy nilly, because letters were expensive, and those basically loow the same, right? So already goofy 16th century spellings gets get goofier with words like “vnto”, “ioyner”, and “beleeue.” In the past I’ve spent hours with a cobbled together workflow using spellchecks and find/replacers to try and fix the problem.

But now I know how to code.

So say hello to Replacer.js. Replacer is a Node.js command line tool designed to execute persistent find/replace commands narrowed by misspellings. In other words, it looks for mispelled words with certain characters, prompts you for a replacement, and remembers that replacement for next time. It allows me to do hours worth of First Folio processing in minutes, and is (almost) modular enough that you can easily customize it for similar projects of your own.

Currently just a 0.1 release, expect a few more updates from me in the near future to flesh out some features before I leave it for others to play with if they so desire. Complete instructions are in the github readme, but here are the highlights:

Installing

First thing to do is to install Node.js and npm. If you don’t know how to do that, you’ll find great instructions here. You’ll also want to go to Replacer.js’s github page and download a zip of the files. Afterwards, open up your command line, navigate over to Replacer’s directory and type:

npm install

Npm will automatically install Replacer.js’s dependencies (readline-sync and spellchecker, if your curious), and you are ready to run it.

Usage

By default Replacer.js will read and change text from the target.txt file provided, and save changed and ignored words to the cipher.json and ignore.json files in the words/ directory. To run replacer with these defaults, simply type into your command line:

node replacer

You can also specify other text files, as many as you like, by typing their relative paths as arguments in the command line, like this:

node replacer macbeth.txt midsummer/act1.txt

In future versions you will also be able to specify different JSON files.

Shortcuts

When running, Replacer will prompt you with any misspelled word containing a ‘u’, ‘v’, ‘j’, or ‘i’ that it hasn’t seen before. That character list is currently hard-coded in, but will soon be easily customizable through another JSON file. When prompted, you can simply ignore the word by pressing enter, type in a new spelling, or use shortcuts to make quick switches. For example, consider the following possible prompts and user responses:

thinke? 

ioyes? j

reuiu'd? v

successiue? successive

vnproued? *

In the preceding example ‘thinke’ will be unchanged, ‘ioyes’ will become ‘joyes’, ‘reuiu’d’ will become ‘reviv’d’, ‘successiue’ will become ‘successive’, and ‘vnproued’ will become ‘unproved’. And Replacer.js will remember the change, never asking about the same word twice.

That’s it!

I had a lot of fun building this tool, and I look forward to using it fthe next time I teach a class on the bard. I’m not sure anyone else will find it useful, but hopefully it’s modular enough thatnsomeone out there can put it to a new purpose. In the meantime, lookout for a new blogpost from me detailing the process of building your own Node.js tool.

Today’s Hack Reactor lesson got off to a challenging start with the sudden introduction of CoffeeScript, the “little language that compiles into JavaScript.” The idea is to give JavaScript developers a way of writing code that is both shorter and cleaner, then compile that code into readable JavaScript. With relatively surprisingly few new commands, CoffeeScript succeeds at rounding off some of JS’s rough edges, and even adds a bit of new functionality.

But despite that svelte profile, there was still a lot of new syntax to take in all at once. A cheat sheet seemed like the way to go, but most of what I found online was cluttered, difficult to read, and sometimes pages long. I wanted a quick reference guide, not an entire tutorial.

So I made one.

If that’s all you were looking for, click on the link and give it a download. One page. All of the good bits. I hope it serves you well. If you you’d like little bit more of a primer, I’ll hit the bullet points below, but you may also want to check out this beginner’s guide, or this in-depth series, and of course the official docs, linked above.

Installing and Running CoffeeScript

CoffeeScript is installed with Node.js’s package manager, npm. If you don’t know what that is, or don’t have it installed, you’re going to want to get that done first. Afterwards, installing CoffeeScript is as simple as going into your command line and typing:

npm -g install coffee-script

You may need to preface that with a sudo, but as always, be careful with that thing. Once you have CoffeeScript installed, it’s time to run it. Navigate to the directory your project is in and type:

coffee --output compiled --map --watch --compile ./

In this case we are telling CoffeeScript to compile every .coffee file in our source directory and save the compiled JavaScript to a folder named “compiled”. By adding that --watched flag, CoffeeScript will look for any changes in the directory, and automatically compile any newly saved files there. Neat. At this point, you may also want to do some googlin’ and see if your text editor of choice supports CoffeeScript syntax highlighting out of the box, or if it needs a plug-in.

The Highlights of CoffeeScript

No ; or {}, and not nearly as much (). CoffeeScript is designed to read a lot like english, so it does away with much of the more extraneous punctuation.

No var keyword. At all. You’ll actually break things if you try to throw var in there. Just assign values directly to a variables, and CoffeeScript will automatically instantiate them at the top of the current scope.

CoffeeScript is white space delimited, so indent deliberately.

fn = -> or fn = (param) -> creates functions. Writing functions is quicker with the arrow notation. You also have the option of leaving off the return keyword, as CoffeeScript automatically returns the last last logically executed line of code (you can explictly return as well if you like).

Bracket [] and dot . notation are essentially unchanged.

CoffeeScript probably has a keyword for that conditional you wanted. and, or, unless, then, is, isnt, yes, no, off, to name a few. Just use > and < for greater than, and less than though

Dynamically create and access arrays with dots. [1...4] will automatically generate the array [1, 2, 3], and [1..4] does the same thing, but includes the last value. Similarly you can create a slice of your existing array with array[2...4].

Classes are much improved. CoffeeScript allows one word Pseudoclassical class creation with the keyword class, class inheritance with the keyword extends, and method inheritance with the keyword super.

Code Comparison

Let’s see it in action:

#Some examples of CoffeeScript code
sum = (x, y=x) -> x + y

arr = [1..10]

arr = for num, i in arr
	sum num, arr[i+1]
	
for num in arr[2...7]
	if num isnt 5 and num is not 7
		console.log "This #{num} is not 5 or 7"
		
		
		
		
		
		
		
		
		
		
//The equivalent JavaScript Code
var sum = function(x, y) {
	y = y || x;
	return x + y;
};

var arr = [];

for (var i = 0; i <= 10; i++) {
	arr.push(i);
}

for (var j = 0; j < arr.length; j++) {
	arr[0] = sum(arr[i], arr[i+1]);
}

for (var k = 2; k < 7; k++) {
	if (arr[k] !== 5 && arr[k] === !7 ) {
		console.log("This" + arr[k] + "is not 5 or 7");
	}
}

The Cheat Sheet

And finally, the cheat sheet linked above. It is by no means exhaustive, but contains examples of most of the most useful CoffeeScript syntax, along with some brief explanations where necessary. Use it as you’d like, and may your JavaScript be a little more caffeinated.

For me, some of the most confusing things as a new JavaScript developer were the keywords this, new, and prototype. Being someone who started with the strongly object oriented language Java (no relation) only made my confusion worse: “I use new to create a new instance of a class? Sounds familiar. But wait, why am I adding methods to a prototype? Seems a bit roundabout. And what exactly is this referring to again???” I was learning what to do by rote, which made mistakes common, trips to google frequent, and coding miserable.

Until last week.

Last week Hack Reactor dropped a bombshell of lesson on me. The mists parted, and three of the most confusing keywords in JavaScript suddenly made sense. It all starts with classes. You see, while some languages are built from the ground up to support object-oriented tools, JavaScript is not one of those languages. So the ways you can build a class are a little more . . . improvised.

Functional Style Classes

var makeDude = function(name) {
	var dude = {};
	
	dude.name = name;
	dude.thumbs = 2;
	dude.greeting = function() {
		console.log("Who has " + dude.thumbs + "thumbs?" + 
		dude.name + " does!");
	};
	
	return dude;
};

var bob = makeDude('Bob');

bob.greeting(); // "Who has 2 thumbs? Bob does!" 

Functional classes are perhaps the most straightforward of the bunch. You want a thing, you make the thing, you return the thing. Our code here allows us to create as many dudes as we like, and we know they’ll all have a name, two thumbs, and a greeting function. It’s easy to follow the code, easy to write the code, and we don’t need to use any weird words.

But, what if we need to make thousands of dudes? Suddenly that greeting function, which is identical for each dude, is starting to hog a lot of memory, needlessly getting remade over and over again. Wouldn’t it be nice if there were a way all the dudes could share one greeting?

Functional-Shared Classes

var makeDude = function(name) {
	var dude = {};
	
	dude.name = name;
	dude.thumbs = 2;
	dude.greeting = dudeMethods.greeting;
	
	return dude;
};

var dudeMethods = {};

dudeMethods.greeting = function() {
	console.log("Who has " + dude.thumbs + "thumbs?" + 
	dude.name + " does!");
};

var bob = makeDude('Bob');

bob.greeting(); // ???

Simple! Easy. We’ve made a separate object dudeMethods to hold all of methods we might want to assign to dudes. And even if we end up with hundreds, we can assign them all in one line of code (if we have (Underscore.js)[http://underscorejs.org] installed) with _extend(dude, dudeMethods);. Now our dudes are all using the same greeting, we’re saving a ton of memory, and still no weird words. Awesome!

Well . . . no, not quite. Unfortunately the above code is broken and will behave in unexpected ways. There is one big step we missed. Now that greeting is being defined outside of makeDude, the variables dude.thumbs and dude.name no longer have any meaning. dude is defined elsewhere, and there is no way for dudeMethods.greeting to have any idea what they are.

That’s where this comes in. It seems like dark magic, but think of this as just another parameter. Just like makeDudes gets a name parameter, greeting function can have a this parameter. The only difference: we pass it in with dot notation. When we call bob.greeting() later, bob will be set to this. So if we rewrite our greeting function slightly…

dudeMethods.greeting = function() {
	console.log("Who has " + this.thumbs + "thumbs?" + 
	this.name + " does!");
};

var bob = makeDude('Bob');

bob.greeting(); // "Who has 2 thumbs? Bob does!" 

The keyword this gets thrown around a lot in JavaScript, with big words like “runtime context”, but just think of it as a parameter, and your life will be much easier. The big exception is when you try to use this in a function that was called without any object to the left of the dot. In that case, it just ends up pointing to the “global scope” (usually the browser window), which is a useless and kind of confusing feature. But hey. JavaScript.

Prototypal Style Classes

var makeDude = function(name) {
	var dude = Object.create(dudeMethods);
	
	dude.name = name;
	dude.thumbs = 2;
	
	return dude;
};

var dudeMethods = {};

dudeMethods.greeting = function() {
	console.log("Who has " + this.thumbs + "thumbs?" + 
	this.name + " does!");
};

var bob = makeDude('Bob');

bob.greeting(); // "Who has 2 thumbs? Bob does!"

The Prototypal method of creating classes in JavaScript, despite its name, does not use the keyword prototype at all. In fact, it’s not much different from Functional-Shared. We still have dudeMethods holding our functions, we’re just taking advantage of Object.create’s ability to make a new copy of an object to save a step or two. Since our dudes start out as copies of dudeMethods, there’s no need to explicitly assign those methods anymore.

Easy enough, but whatever happened to new and prototype?

Pseudoclassical Style Classes

var Dude = function(name) {
	this.name = name;
	this.thumbs = 2;
};

Dude.prototype.greeting = function() {
	console.log("Who has " + this.thumbs + "thumbs?" + 
	this.name + " does!");
};

var bob = new Dude('Bob');

bob.greeting(); // "Who has 2 thumbs? Bob does!"

“What in heaven’s name is this now?!? Where did all of the code go? If this is an object calling a function shouldn’t it refer the browser window here? What the heck are new and prototype doing anyway???” Believe it or not, this code is actually very similar to the Prototypal class from before.

The big thing to understand is that the keywords new and prototype are conveniences ginned up in order to save developers from writing a bit of code. Nothing particularly new is happening under the hood. For example, prototype is nothing more than an object automatically created by JavaScript and attached to every function (remember that in JavaScript, functions are themselves objects, which means that they can have their own properties). Dude.prototype is very similar to dudeMethods from before, the big difference being we didn’t have to build it ourselves.

What about new? Well, that one is a little stranger, but still not so different from what we’ve seen before. By calling a function with the new keyword, we call it in “constructor mode”, which means nothing more than that JavaScript will automatically insert two lines of code for us: one to set this to a newly created copy of the function’s prototype, and one to return this. In other words, when we actually run new Dude() above, the code it will look like more like this:

var Dude = function(name) {
	this = Object.create(Dude.prototype); // <-- automatically created at runtime
	this.name = name;
	this.thumbs = 2;
	return this; // <-- automatically created at runtime
}

Almost identical to our Prototypal class from before! We can clearly see why this doesn’t refer to the browser window. The very first line of the code now explicitly sets this to be something else. JavaScript could have used “obj”, “instance”, or anything else to store the copy of prototype, but the designers chose this. It was already a reserved word and would otherwise serve little purpose inside a constructor function like Dude. A decision that would later confuse thousands of new developers like me, and possibly you.

TL;DR

  • JavaScript was not built with classes in mind, and so has had to hack together different, sometimes odd, ways of creating them.
  • The keyword this is basically just another parameter for your functions, and will always refer to the object that called the function (i.e. for “obj.func()”, obj isthis).
  • Unless, of course, this is explicitly overridden, such as by the keyword new or by the ‘call’, ‘apply’, and ‘bind’ methods.
  • Or if the function wasn’t called by an object at all, because then this will refer to global scope (i.e. the window), because reasons.
  • A prototype is just an object which is automatically generated as a property of every function. It’s used to store methods we would like every “instance” of the function to have (and for inheritance, but don’t worry about that for now).
  • The keyword new calls your function in “constructor mode”, automatically inserting two lines of code. One at the beginning which sets this to be a copy of the prototype, and one at the end which returns this.