just some sort of lame blog

JavaScript is just as easy as Ruby (even without jQuery!)

Ernie sent this ruby snippet and marveled at its brilliant simplicity:

class Date  
  def at_some_point  
end # => Tue May 21 10:23:00 -0500 2008 # => Tue May 21 02:10:00 -0500 2008 # => Tue May 21 18:28:00 -0500 2008 # => Tue May 21 07:25:00 -0500 2008

I recalled using Date.prototype in JavaScript in the past to add some helpful date functions, so I thought I'd see if I could write a similar function just as elegantly:

Date.prototype.atSomePoint = function() {
    return new Date(rand(this.atMidnight().valueOf(), this.tomorrow().atMidnight().valueOf()));

new Date().atSomePoint();   \\ Wed May 21 2008 06:33:28 GMT-0400 (Eastern Daylight Time)
new Date().atSomePoint();   \\ Wed May 21 2008 12:57:13 GMT-0400 (Eastern Daylight Time)
new Date().atSomePoint();   \\ Wed May 21 2008 08:37:44 GMT-0400 (Eastern Daylight Time)

Unfortunately .atMidnight() and .tomorrow() don't exist in JavaScript's Date object by default (that I know of), so I had to write those helpers as well as a random number helper, rand():

Date.prototype.atMidnight = function() {
    return this;

Date.prototype.tomorrow = function() {
    this.setDate(this.getDate() + 1);
    return this;

function rand(lowerBound, upperBound) {
    return Math.floor((upperBound - (lowerBound - 1)) * Math.random()) + lowerBound;

While I probably would never find a use for .atSomePoint(), it certainly was easy enough to write.


Archived Comments

Adam Lindsay Any modern language should be able to produce functionality that any other language can. Just because Javascript is capable of it, doesn't make it as simple, easy or elegant. I have been impressed with JavaScript lately and the advances the libraries have taken it. JQuery of course comes to the top of that list.

In 5 lines though, Ernie was able to mixin the function straight to the Date class. Took you 16 lines and an external library. Not only that but Javascripts syntax is littered with parens, semicolons, and declarations like return and new.

This might be a small example, but in terms of cost, you just showed me that it takes Javascript 3x as long. Not only that, but with the heavier syntax, any modifications will add additional time to track down what is exactly going on. Imagine this on a much larger scale.

Just as Easy? Thats certainly debatable.
travis No external libraries were used or are necessary for that JS code to work. Date.prototype extends the native JavaScript Date class to add the new functions.

The main advantage is that anyone who's ever worked with any ECMAScript-based language (C++, JScript, Java, C#, J#, etc...) can understand what's going on in JavaScript, not so in Ruby.

Imagining it on a much larger scale, how many ECMAScript-based language devs are out there vs Ruby devs? also: Ruby scales? Also, it will run on any OS with a graphical web-browser.

comments powered by Disqus