NIH/WTF

TorgoX on 2005-09-24T09:19:20

Dear Log,

I'm finding that here in the badlands of JavaScriptia, Not-Invented Here is about the only way to stay sane.

Because, you see, most JavaScript is so very bad. For example, here's a random-quote generator I found the other day, with its data table and output thingy simplified in order to expose the code's dark heart.

quote0="One"
quote1="Two"
quote2="Three"
quote3="Four"
quote4="Five"

total = 4;
today2 = new Date();
today = today2.getTime() / 10;
rnd = eval(round(today % total, 0));

while (0 > rnd > total){
    today2 = new Date();
    today = today2.getTime() / 10;
    rnd = eval(round(today % total, 0));
}

alert(eval("quote"+rnd));

function round(number,X) {
    return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

I mean, just look at it.

It's horrible in every way.

And this is actually typical of the past ten years of JavaScript that is smeared all over the Net.

Here's my rewrite:

var quotes = [
  "One",
  "Two",
  "Three",
  "Four",
  "Five"
];
var i = Math.floor(
  quotes.length * Math.random()
);
alert( quotes[i] );

Or if I want to get fancy:

Array.prototype.randomElement =
function        randomElement () {
  if(this.length == 0) return null;
  return this[ Math.floor(
    this.length * Math.random()
  )];
};

var quotes = [
  "One",
  "Two",
  "Three",
  "Four",
  "Five"
];

alert( quotes.randomElement() );

Or if you really don't trust Math.random(), you can always use this:

Array.prototype.randomElement =
function        randomElement () {
  if(this.length == 0) return null;
  return this[
    new Date().getTime() % this.length ]
  ];
};