If Hemingway wrote JavaScript

The following article was written by my good friend and colleague, [Angus Croll](//twitter.com/angustweets). Angus works on the web core team at twitter, talks at conferences around the world, and runs an amazing [blog](//javascriptweblog.wordpress.com) on javascript. Beyond this, he’s also a huge book nerd, so I thought it would be fun to get him to write about code from that perspective. Check it out! And let us know what you think on [twitter](//twitter.com/angustweets)!


The New Book “If Hemingway wrote JavaScript” is out in September 2014.
Pre-order your copy here!


I loved literature long before I ever wrote a line of code. Now I write JavaScript, lots of it, and I’m writing a book about it.

What is it about JavaScript that attracts so many literature devotees? I have a few half-baked theories relating to the expressive potential of a limited syntax, but that’s for another time. What about the great writers? What would they have made of JavaScript? Even as a long-time Hemingway nut, I’d be the first to admit that Papa would probably have loathed programming (and programmers). Yet I’m betting that amongst all that general contempt there would have lurked a soft spot for JavaScript, because it’s his kind of language, am I right? A spare and deceptively plain surface, masking substance and drama beneath.

The Mother of all Code Reviews #

hemingway.png

Recently I had a dream in which I asked Hemingway and four other literary luminaries to write some JavaScript for me; specifically a function that returned a fibonacci series of a given length. Interestingly each author chose to solve the problem in a different way. They did pretty well actually - as far as I can tell every solution works as advertised (yes, even Andre Breton’s). Here’s what I got:

Ernest Hemingway #

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;
    result.push(next);
  }
  return result;
}

No surprises here. Code reduced to its essentials with no word or variable wasted. It’s not fancy; maybe its even a little pedantic - but that’s the beauty of Hemingway’s writing. No need for elaborate logic or clever variable names. It’s plain and its clear and it does what it has to - and nothing more.

Hemingway didn’t suffer fools gladly so if you ask for a series with less than two numbers he’ll just ignore you. “I’m tired and this question is idiotic”.

William Shakespeare #

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;

  //[Exuent]
}

The Bard gets a little wordy here but we wouldn’t have it any other way. Notice how the comments (other than titular captions and stage directions) are written in iambic pentameter - a meter of ten paired syllables with the stress falling on the second syllable of each pair (or foot). In his plays Shakespeare often adds dramatic emphasis by deviating from strict iambic pentameter — he might add an extra syllable or use an alternate stress. It looks as though he’s using the same trick in this coding exercise. Way to go Will.

Andre Breton #

function Colette(umbrella) {
  var staircase = 0, galleons = 0, brigantines = 1, armada = [galleons, brigantines], bassoon;
  Array.prototype.embrace = [].push;

  while(2 + staircase++ < umbrella) {
    bassoon = galleons + brigantines;
    armada.embrace(brigantines = (galleons = brigantines, bassoon));
  }

  return armada;
}

As a founding member of the surrealist movement, Breton believed dreams were more interesting than reality and should form the basis of our creative endeavors. Nouns are chosen accordingly. Although it’s easy to knock Breton, his work has aged well and is invariably heartfelt and beautiful - an unconscious upwelling of imagery folded into his own conscious expression. Here’s a translation of the gorgeous poem Facteur Cheval.

Breton has most likely named his fibonacci exercise after an old flame, while he imagines the resulting collection as a fleet of ancient vessels. The solution is underscored by characteristically elegant logic - he’s using a comma operator to simultaneously shift elements between galleons, brigantines and bassoons. Hats off Andre!

Roberto Bolano #

function LeonardoPisanoBigollo(l) {

  if(l < 0) {
    return "I'd prefer not to respond. (Although several replies occur to me)"
  }

  /**/

  //Everything is getting complicated.
  for (var i=2,r=[0,1].slice(0,l);i<l;r.push(r[i-1]+r[i-2]),i++)

  /**/

  //Here are some other mathematicians. Mostly it's just nonsense.

  rationalTheorists = ["Archimedes of Syracuse", "Pierre de Fermat (such margins, boys!)", "Srinivasa Ramanujan", "Rene Descartes", "Leonhard Euler", "Carl Gauss", "Johann Bernoulli", "Jacob Bernoulli", "Aryabhata", "Brahmagupta", "Bhaskara II", "Nilakantha Somayaji", "Omar Khayyám", "Muhammad ibn Mūsā al-Khwārizmī", "Bernhard Riemann", "Gottfried Leibniz", "Andrey Kolmogorov", "Euclid of Alexandria", "Jules Henri Poincaré", "Srinivasa Ramanujan", "Alexander Grothendieck (who could forget?)", "David Hilbert", "Alan Turing", "von Neumann", "Kurt Gödel", "Joseph-Louis Lagrange", "Georg Cantor", "William Rowan Hamilton", "Carl Jacobi", "Évariste Galois", "Nikolay Lobachevsky", "Rene Descartes", "Joseph Fourier", "Pierre-Simon Laplace", "Alonzo Church", "Nikolay Bogolyubov"]

  /**/

  //I didn't understand any of this, but here it is anyway.
  return r

  /**/

  //Nothing happens here and if it does I'd rather not talk about it.
}

If you don’t read at least one Bolano book before you die then you’ve wasted your life. Bolano’s writing is remarkable; at once effortlessly sophisticated and charmingly naive - his narrative style is characterized by a disarmingly winsome honesty. No aspect of human frailty is off limits, but the warmth and humour with which every foible is conveyed is both engaging and uplifting.

True to form, Roberto’s exam paper is peppered with admissions of insecurity, embarrassment and ignorance. The solution, though rather brilliant, is presented as something of an afterthought. Always the obsessive, always tangential, he’s much happier offering us a mildly interesting but ultimately useless list of mathematical genii.

There are other Bolano traits here - the juxtaposition of long and short paragraphs, the absence of semicolons (mirroring the absence of quotation marks in his novels), and the use of implicit globals - suggesting that each variable is destined to make further appearances in subsequent chapters.

Charles Dickens #

function mrFibbowicksNumbers(enormity) {
  var assortment = [0,1,1], tally = 3, artfulRatio = 1.61803;

  while(tally++ < enormity) {
    //here is an exceedingly clever device
    assortment.push(Math.round(assortment[tally-2] * artfulRatio));
  }

  //should there be an overabundance of elements, a remedy need be applied
  return assortment.slice(0, enormity);
}

I’m not a fan of Dickens. Mostly I agree with Henry James’ damning assessment:

“If we might hazard a definition of his literary character, we should, accordingly, call him the greatest of superficial novelists. We are aware that this definition confines him to an inferior rank in the department of letters which he adorns; but we accept this consequence of our proposition. It were, in our opinion, an offense against humanity to place Mr. Dickens among the greatest novelists. For, to repeat what we have already intimated, he has created nothing but figure. He has added nothing to our understanding of human character.”

Boz’s superficiality is borne out by his fibonacci solution. Yes, there are some mildly amusing names, but a complete lack of substance and understanding at its heart. He has failed to appreciate the underlying philosophy of the fibonacci series and has instead resorted to bludgeoning his way through the problem with multiplication. Sigh.

Closing thoughts #

Whether it’s Crockford’s protective albumen or the dry and narrow minded confines of computer science classes, doctrine and dogma are the enemies of good JavaScript. Some developers like rulebooks and boilerplate - which is why we have Java. The joy of JavaScript is rooted in its lack of rigidity and the infinite possibilities that this allows for. Natural languages hold the same promise. The best authors and the best JavaScript developers are those who obsess about language, who explore and experiment with language every day and in doing so develop their own style, their own idioms, and their own expression.

That’s all. Hope you enjoyed it. It’s mostly nonsense.

 
7,246
Kudos
 
7,246
Kudos

Now read this

deep emo shit

The other day in IRC my good friend Divya brought up Dustin Curtis’s recent blog posts by saying “it seems like he’s so sad.” I agreed. To be sure, Dustin’s more recent writing covers topics that his blog has been more or less focusing... Continue →