There’s Poetry in that Code: If Hemingway Wrote JavaScript

A new book exploring the intersection of literature and code is a delightful romp through some of the Western world’s most celebrated writers and the imagined JavasScript they would have — could have — slung had they been so inclined.

Written and compiled from submissions by Angus Croll, an engineer at Twitter, If Hemingway Wrote JavaScript celebrates literature and code in equal measure.

In particular, Croll explores the literary achievements and style of his authors — Virginia Woolf, Franz Kafka and David Foster Wallace among many others — and then imagines the JavaScript they’d write to tackle specific problems. For Croll, JavaScript is the “most literary of computer languages,” and like literature it’s open to conceptual breakthroughs based on the imagination of those writing it.

Reading through the book, we’re reminded that “although [Jack] Kerouac claimed to dislike the period and mistrust the comma, he used both liberally.” Or, “by the time he wrote Ulysses, [James] Joyce had abandoned narrative  authority entirely, in favor of an urgent, in-the-moment stream of consciousness in which both narrator and protagonist relate disjointed scraps of ephemera that mirror the random, cluttered, ever-changing character of interior thought.”

Or, take this intro to Tupac Shakur:

It’s hard to reconcile the two identities of Tupac Amaru Shakur. One was cerebral, sensitive, and compassionate: an actor and poet in his early teens, a devotee of Shakespeare who addressed women’s struggles, child abuse, and poverty in his lyrics. The other was a violent, gun-toting embodiment of the gangsta rap movement: in and out of prison and sporting a “Thug Life” tattoo across his stomach, killed at the age of 25 by an unknown attacker’s bullet.

All of which is to say that like authors and their telltale innovations, some programming languages lend themselves to a wide degree of stylistic expression.

Via If Hemingway Wrote Javascript:

JavaScript has plenty in common with natural language. It is at its most expressive when combining simple idioms in original ways; its syntax, which is limited yet flexible, promotes innovation without compromising readability. And, like natural language, it’s ready to write…

…Natural language has no dominant paradigm, and neither does JavaScript. Developers can select from a grab bag of approaches—procedural, functional, and object-oriented—and blend them as appropriate. Most ideas can be expressed in multiple ways, and many JavaScript programmers can be identified by their distinct coding style.

The book is divided into five “assignments” with each devoted to a few authors producing code to solve a given problem. The first assignment is to write a function that “returns the first n numbers of the Fibonacci sequence.” The Fibonacci sequence, in turn, is a series of numbers where each is the sum of the previous two. For example: 0, 1, 1, 2, 3, 5, 8, 13, etc.

Croll gets things started with the book’s namesake, Ernest Hemingway, whose prose, we’re reminded, “is never showy, and his syntax is almost obsessively conventional. The short, unchallenging sentences and absence of difficult words add a childlike quality to his cadence. He assumes the role of naive observer, all the better to draw his readers into the emotional chaos beneath.”

Here’s what Hemingway’s JavaScript looks like as he tackles the Fibonacci assignment:

function fibonacci(size) {

     var first = 0, second = 1, next, count = 2, result = [first, second];

     if (size < 2)
          return "the request was made but it was not good"

     while (count++ < size) {
          next = first + second;
          first = second;
          second = next;
     return result;

Short. Concise. To the point. Or, in Croll’s analysis:

Hemingway’s Fibonacci solution is code reduced to its essentials, with no word or variable wasted. It’s not fancy — maybe it’s even a little pedantic — but that’s the beauty of Hemingway’s writing. There’s no need for elaborate logic or showy variable names. Hemingway’s JavaScript is plain and clear, and it does only what is necessary—and then it gets out of the way to allow the full glory of the Fibonacci sequence to shine through.

William Shakespeare comes next. Here’s the bard tackling the same problem:

function theSeriesOfFIBONACCI(theSize) {

     //a CALCKULATION in two acts
     //employ'ng the humourous logick of JAVA-SCRIPTE

     //Dramatis Personae
     var theResult; //an ARRAY to contain THE NUMBERS
     var theCounter; //a NUMBER, serv'nt to the FOR LOOP

     //ACT I: in which a ZERO is added for INITIATION

     //[ENTER: theResult]

     //Upon the noble list bestow a zero
     var theResult = [0];

     //ACT II: a LOOP in which the final TWO NUMBERS are QUEREED and SUMM'D

     //[ENTER: theCounter]
     //Commence at one and venture o'er the numbers
     for (theCounter = 1; theCounter < theSize; theCounter++) {
          //By divination set adjoining members
          theResult[theCounter] = (theResult[theCounter-1] || 1) +
          theResult[Math.max(0, theCounter-2)];

     //'Tis done, and here's the answer
     return theResult;


Shakespeare, as Croll reminds us, played with the iambic pentameter popular in his time by deviating where stressed syllables lay and sometimes adding an extra syllable as well. His JavaScript doesn’t hesitate to do so either.

Notice that although Shakespeare’s comments are in iambic pentameter, he’s using weak endings (that is, adding an extra unstressed syllable). Shakespeare frequently used weak endings to denote enquiry or uncertainty (the Elizabethan equivalent of upspeak).

If Hemingway Wrote JavaScript should delight the nerdier fans of both literature and code, satisfying each whether they’re familiar with the authors or the inner workings of JavaScript.

As Croll writes, part of his effort is to bridge the gap between the humanities and computer science. The result, this book, is amazingly well done.

Images: Illustrations of William Shakespeare, Jack Kerouac, Jane Austen, James Joyce, Tupac Shakur, Virgina Woolf, David Foster Wallace, Sylvia Plath, JK Rowling and Rundhati Roy, via If Hemingway Wrote Javascript. Select to embiggen.



Javascript project by Ian Pearce lets you draw and create Magic Eye pictures in your browser:

MagicEye.js is a JavaScript library for generating “Magic Eye” images in the browser. Technically, it generates single-image random dot stereograms, or SIRDS.

… pixel values from an HTML5 Canvas are turned into depth data, which are then used to generate a Magic Eye image.

Try it out for yourself here

Homestuck Style Fireflies for your Tumblr Blog!

Hi there guys!  I’m sure you’ve all seen these nifty little fireflies that float around the screen in A6A6I4.


I have spent some time optimizing these little fellows for YOUR VERY OWN TUMBLR BLOGS.

That’s right, you can add these to your existing Tumblr theme.

It’s pretty simple, and for you tech-savvy Tumblr users out there, I’ll go ahead and give you all of the code in one go (at the bottom of this post).  It’s pretty simple, and there’s only a couple things you have to do.

Step 1.

Look for the Edit HTML section of your blog.  Go until you can see your code.

Once you have your code open, one line above <html> paste the following:

<link href=”” rel=”stylesheet” type=”text/css” />

This gets some styling from MSPA’s site.

It should look vaguely like this:


Take note of one thing: at the very top, the <!DOCTYPE HTML> tag should be there.  It does not have to be exactly as you see in the screenshot, however, if no DOCTYPE HTML tag appears, add:

<!DOCTYPE HTML> to the very top of your code.

Step 2.

Scroll down until you see <body>

If you have lots of code, you can do a page search with CTRL+F (CMD+F on Mac) for <body>.

One line below <body>, paste the rest of the code.  The rest of the code will be posted after the last bit of this post.

Once you add the last bit of code, you’re good to go!  The Fireflies should be up on your blog.

JavaScript and HTML savvy bloggers can even add more fireflies.  The method to do so involves changing the variable “boxnum” in the Javascript, and adding a new <canvas id=”fbox_X” class=”boxtemplate” style=”top: 500px; left: 700px;”></canvas> tag where X is 1 number more than the last canvas.  You will have to tweak positions.

Here’s what it looks like on my blog:


The last bit of code (this is a LOT of code, copy it all and copy it right!)

Feel free to send me an ask if you have any issues, and if you use it, maybe send me an ask so I can see it in action!

Last bit of code:

<script type=”text/javascript”>
//Code (c) MSPA, distributed for use on Tumblr by hotchameowmile
// JavaScript Document// firefly canvas display engine… LGL
// ————————————————- DRY method (Do not Repeat Yourself codewise
// RANDOM NUMBER GENERATOR— results = whole number no decimals
// The (nmod) provides a modifier that adds an extra amount to the outcome.
// nmin = minimum number
// nmax = maximum number
// EXAMPLE: randnum (0, 10, 0) = random number between 0 and 10
// EXAMPLE: randnum (0, 50, 2) = random number between 0 and 50… adds +2 to the returned result
function randnum(nmin, nmax, nmod) {
return ((Math.floor(Math.random() * (nmax - nmin + 1)) + nmin) + nmod);

// IMAGE LOADER function - need to load the image to the canvas block so it will be seen
// IMG Loader = handles setting up both ‘Right’ facing and ‘Let’ facing image animates for each canvas block
// IMG not loaded = you will not see anything.
function make_img(c)
beer[c] = new Image();
beel[c] = new Image();
beer[c].src = sbeer[c];
beel[c].src = sbeel[c];
beer[c].onload = function(){
cobj[c].drawImage(beer[c], 0, 0);
beel[c].onload = function(){
cobj[c].drawImage(beel[c], 0, 0);

// VARIABLE and OBJECT ITEM code below
// FIXED Width and Height sizes (200 x 150)
var w =200, // width of a canvas box
h =150, // height of a canvas box
fmax = 24 // the maximum number of frames in the animated .gif file
radius =60, // collision size to check hitting box edge. Smaller= closer to edge, Larger = further away from edges
bounceFactor =1, // smooth animation… movement moves at 1 point a second. Increasing will make item move faster
xx = w - 60, // x adjustment for placing firefly xcoord so it is not outside box
yy = h - 60, // y adjust for placing firefly ycoord so it is not outside box
fpsrate = 15, // Change Frames Per Second Rate. Determines whole screen refreshing rate (lower = slower, higher = faster)
boxnum = 4; // IMPORTANT ==== Contains the number of <canvas> animation boxes you want on screen.
// boxnum was equal the same number of <canvas id=”fbox_1”, “fbox_2”, etc..> boxes you have in your HTML page.
// Any missing boxes or skipping numbers will break the display.

//NOTE FOR CUSTOMIZING: boxnum MUST be changed to add/remove fireflies.
// OBJECTS for animation
var cobj =[]; // object storing the ‘canvas’ playground box
var beer =[]; // Bee Right- facing image container for a <CANVAS>
var beel =[]; // Bee Left- facing image container for a <CANVAS>
var sbeer =[]; // Bee Right- Storage container to hold IMG source name for a <CANVAS> - to transfer info to object
var sbeel =[]; // Bee Left- Storage container to hold IMG source name for a <CANVAS> - to transfer info to object

// BUILD object to hold all ‘firefly’ instances
var firefly = {};

// START BUILDING ALL NEEDED firefly objects
for (var x = 0; x < boxnum; x++) {
var sname = document.getElementById(‘fbox_’ + x); // Get the ID or name of canvas object
sname.width = w; // FORCE canvas block to be a specific width size
sname.height = h; // FORCE canvas block to be a specific height size

var tname = document.getElementById(‘fbox_’ + x).getContext(‘2d’); // Attach the full ‘canvas’ controls to make it work
cobj.push(tname) // The Object ID container for a specific <canvas> box

// Create needed images! - R and L facing types (BEER - right, BEEL - left)
sbeer.push(“”); // firefly facing right sprite sheet load - img source must be found here
sbeel.push(“”); // firefly facing left sprite sheet load - img source must be found here
make_img(x); // Call IMAGE CREATOR function for a <canvas> box

// CREATE a FIREFLY object to store its personality or specifics - IMPORTANT.
// This OBJECT allows to control and maintain large numbers of entities and makes programming simpler to maintain
firefly[x] = {
dir: randnum(0, 1, 0), // random num from 0 to 1 (0 = move left, 1 = move right)
x: randnum(0, xx, 0), // place img random x coord
y: randnum(0, yy, 0), // place img random y coord
xvel: randnum(0, 3, 1), // xmovement velocity
yvel: randnum(0, 3, 1), // ymovement velocity
imgw: 60, // img width
imgh: 60, // img height
frame: randnum(0,fmax,0), // animation frame to start from- usually 0
tick: randnum(0,fmax,0), // anim frame counter… each number is a frame in img animation
tx: 0, // temporary x value to track which anim frame is viewed
framemax: 12, // max number of animation frames in img (firefly = 24 frames). Stack always starts at 0 so minus 1!
delay :0, // delay flag to stop gif/sprite animation before repeating cycle
delaytick :0 // stores the delay counter

// FUNCTION - CLEAR canvas screen.
// Erases content of box before new updated motions are ‘drawn’ - IMPORTANT do not erase
function clearCanvas(i) {
cobj[i].clearRect(0, 0, w, h);

// ANIMATION function - go move RIGHT
function drawr(i){
// firefly[i].frame = firefly[i].tick % firefly[i].framemax; // frame counter stays between 0 and maxframes (23)
// firefly[i].frame ++;
if (firefly[i].frame > firefly[i].framemax) {
firefly[i].frame = 0;
firefly[i].delay = 1;
firefly[i].delaytick = 0;
firefly[i].tx = firefly[i].frame * firefly[i].imgw; // moves animation block to next frame on sprite sheet
cobj[i].drawImage(beer[i],firefly[i].tx,0,firefly[i].imgw,firefly[i].imgh, // DISPLAY Bee Right image anim
if (firefly[i].delay){
firefly[i].delaytick ++;
if (firefly[i].delaytick > fpsrate){
firefly[i].delay = 0;
firefly[i].delaytick = 0;
} else {
firefly[i].frame++ // move to next animation frame
cobj[i].restore(); // done updating the canvas- close task!
// ANIMATION function - go move LEFT
function drawl(i){
// firefly[i].frame = firefly[i].tick % firefly[i].framemax; // frame counter stays between 0 and maxframes (23)
// firefly[i].frame ++;
if (firefly[i].frame > firefly[i].framemax) {
firefly[i].frame = 0;
firefly[i].delay = 1;
firefly[i].delaytick = 0;
firefly[i].tx = firefly[i].frame * firefly[i].imgw; // moves animation block to next frame on sprite sheet
cobj[i].drawImage(beel[i],firefly[i].tx,0,firefly[i].imgw,firefly[i].imgh, // DISPLAY Bee Right image anim
if (firefly[i].delay){
firefly[i].delaytick ++;
if (firefly[i].delaytick > fpsrate){
firefly[i].delay = 0;
firefly[i].delaytick = 0;
} else {
firefly[i].frame++ // move to next animation frame
cobj[i].restore(); // done updating the canvas- close task!

// ANIMATE all the FIREFLY boxes function
function update(){
for (var i = 0; i < boxnum; i++) { // CYCLE through all canvas boxes you want - use BOXNUM variable
clearCanvas(i); // Clear canvas screen before showing new animation content
// DISPLAY correct facing animation (LEFT or RIGHT)
if (firefly[i].dir) {
drawr(i); // moving to Right - firefly face right
} else {
drawl(i); // moving to Left - firefly face left
// Now, lets make the firefly move to a new position
firefly[i].y += firefly[i].yvel;
firefly[i].x += firefly[i].xvel;

// EDGE collision check - BOTTOM BOX COLLISION
if(firefly[i].y + radius > h) {
firefly[i].y = h - radius;
firefly[i].yvel = randnum(1,2,1); // random ymove rate! random (2) + 1
firefly[i].yvel *= -bounceFactor; // change direction
// EDGE collision check - TOP BOX COLLISION
if(firefly[i].y - radius < -60) {
firefly[i].yvel *= -bounceFactor; // change direction
firefly[i].y += firefly[i].yvel;
firefly[i].yvel = randnum(1,2,1); // random ymove rate! random (2) + 1
// EDGE collision chek - RIGHT BOX COLLISION
if (firefly[i].x + radius > w) {
firefly[i].dir = 0; // change firefly facing direction
firefly[i].x = w - radius;
firefly[i].xvel = randnum(1,2,1); // random ymove rate! random (2) + 1
firefly[i].xvel *= -bounceFactor;
// EDGE collision chek - LEFT BOX COLLISION
if (firefly[i].x - radius < -60) {
firefly[i].dir = 1; // change firefly facing direction
firefly[i].xvel *= -bounceFactor;
firefly[i].x += firefly[i].xvel;
firefly[i].xvel = randnum(1,2,1); // random ymove rate! random (2) + 1
setInterval(update, 1000/fpsrate); // change FPSRATE to adjust canvas refreshing rate - reg speed is 24 fps. Higher = more demanding


How to: Why do people put code like "throw 1; " and "for(;;);" in front of json responses?

How to: Why do people put code like “throw 1; ” and “for(;;);” in front of json responses?

Why do people put code like “throw 1; <dont be evil>” and “for(;;);” in front of json responses?

Possible Duplicate:
Why have “while(1);” in XmlHttpRequest response?
Why does Google prepend while(1); to their JSON responses?

Google returns json like this:

throw 1; <dont be evil> { foo: bar} 

and Facebooks ajax has json like this:

for(;;); {"error":0,"errorSummary": ""} 
  • Why do they put code that…

View On WordPress

Pluck And Unique in JavaScript

Functional programming is most powerful when you combine a set of simple functions together in useful ways. For example, from some API you retrieve a list of vehicles:

var vehicles = [
  {name: 'mx-5', type: 'car', price: 20000},
  {name: 'ninja', type: 'motorcyle', price: 10000},
  {name: 'enzo', type: 'car', price: 1000000}

And you want to get the number of types:

var types = {};
vehicles.forEach(function(vehicle) {
    types[vehicle.type] = true;
var typeNumber = Object.keys(types).length;

console.log(typeNumber);// 2

That was somewhat cumbersome for such a simple operation. It would be even worse for < IE 9 as Object.keys would not exist. But by using pluck, which takes all values of a key in an array of object. And unique which removes duplicate values in an array, this is easy:

var typeNumber = unique(pluck(vehicles, 'type')).length;
console.log(typeNumber);// 2

The unique and pluck functions are just the vehicle type checking code abstracted and modularized:

var unique = function(arr) {
    var types = {};
    arr.forEach(function(element) {
        types[element] = true;

    return Object.keys(types);

var pluck = function(arr, type) {
    var plucked = [];
    arr.forEach(function(element) {

    return plucked;

Similar functions are available in libraries like Lo-Dash, but I still think it is important to know how they work and why they exists.

Github Location:

Okay, so, a post came across my dashboard recently, containing this pie chart from a reddit thread.

Because I’m a big weirdo, this graph was not good enough for me.  If I’m going to look at information about the deaths of Roman emperors, I want to know which emperors died from which causes.  And so, I made a thing because I could.

It isn’t terribly pretty because I’m not well versed in javascript, but it exists.

A program that generates actuallies

Actually, it’s about onslaughts in midway Frenchmen #caughtgate
Actually, it’s about intercessions in process shopliftings #iniquitygate
Actually, it’s about perusals in xxvii dominances #ligamentgate
Actually, it’s about statements in emissary defections #drankgate
Actually, it’s about archeries in timid draftings #self-#controlgate
Actually, it’s about assignments in suspended solitudes #civilisationgate
Actually, it’s about inaugurations in joyful diagnoses #manifestogate
Actually, it’s about tickers in conditioned draftings #deliverancegate
Actually, it’s about rapidities in assigned allocations #hammockgate
Actually, it’s about tycoons in engraved indicators #dedicationgate
Actually, it’s about actualities in arrested vulnerabilities #carcassgate

3 Regrets I have (so far) as a Self-Taught Coder

I’ve made a huge mistake.

About a month ago I realized I was not learning what I wanted to be. Or should be. So I switched programming languages/frameworks. Again.

thought Ruby on Rails was the way to go … But then, after months of learning, I decided to switch gears and focus on JavaScript along with Meteor. (And I am glad I switched.)

Of course, I wish I would have made the transition sooner. A lot sooner.

Here are my three biggest regrets since I started teaching myself how to code about a year and a half ago.

1. Given up Ruby on Rails sooner.

Before I embarked on learning Ruby on Rails (RoR), I spent over three months learning the fundamentals of programming with Python. I decided to make the transition to Ruby when I decided to try to build my own web apps. And Rails seemed like the better fit than Django.

There were many reasons why RoR was better for me than Python and Django. It’s too much to get into now. But the switch at that time was wise.

What I wish I did differently, though, was try Meteor earlier on….

Read the full article  here.

I haven’t talked about Twine in quite a while, but Twine 2 was just released, and it has a web version as well as a download version! The syntax has been changed completely, but it’s definitely changed for the better. So if you’re used to Twine 1’s macro syntax, you’ll have to get used to the new syntax, but once you do, I think you’ll be happy with its very nice, human-readable format.

All the details are not yet in the Twine wiki (except for an important little introductory guide thing here:, but you can see all the details available and learn all the new syntax stuff from, so definitely check that out before you dive in!

If you’ve somehow gone without hearing about Twine, it’s a program for easily making non-linear interactive text-based games/stories, which is a pretty core skill to learn for making video games with stories. So if you’re interested in making video games but don’t have the skill to program or make art or music or whatever or don’t know how or where to start, this is a great option! Write your stories and as you learn programming stuff, you can expand your stories’ capabilities with JavaScript and learn how to display images and play music and sound effects for your text games! Check out twinegarden on Tumblr to see a nice collection of Twine games that people submit links to with pictures of their Twine webs, and visit for free hosting for your completed Twine games!

It’s a pretty fantastic tool with a pretty awesome community, and it’s definitely worth checking out! :)