Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

TorgoX (1933)

TorgoX
  sburkeNO@SPAMcpan.org
http://search.cpan.org/~sburke/

"Il est beau comme la retractilité des serres des oiseaux rapaces [...] et surtout, comme la rencontre fortuite sur une table de dissection d'une machine à coudre et d'un parapluie !" -- Lautréamont

Journal of TorgoX (1933)

Saturday September 24, 2005
04:19 AM

NIH/WTF

[ #26870 ]
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"

tota l = 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 ]
  ];
};

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.