Adding JavaScript methods to Number

TorgoX on 2005-09-09T05:01:09

Dear Log,

Some aimless JavaScript fun. Try it:

var protonum = (1).constructor.prototype;

protonum.upTo = function upTo (n, closure) {
  var orig_i = this;
  if(this > n) return;
  for(var i = orig_i; i <= n; i++) {
    closure( i, orig_i, n);
  }
  return;
};

protonum.chr = function chr() { // perlish
  return String.fromCharCode(this);
}; 

protonum.th = function th() {    // as in num.th
  return this.toString() + this.th_suf();
};

protonum.th_suf = function th_suf() {
  var n = Math.abs(this);
  if(n != Math.floor(n))
   return 'th'; // least-bad, I guess.
  
  n %= 100;
  if(n == 11 || n == 12 || n == 13) return 'th';
  n %=  10;
  if(n == 1) return 'st';
  if(n == 2) return 'nd';
  if(n == 3) return 'rd';
  return 'th';
};

( 100 ).upTo( 112, function(i){
  print( "The " + i.th() + " character is "
    + i.chr() + "\n"
  );
});

Output:

The 100th character is d
The 101st character is e
The 102nd character is f
The 103rd character is g
The 104th character is h
The 105th character is i
The 106th character is j
The 107th character is k
The 108th character is l
The 109th character is m
The 110th character is n
The 111th character is o
The 112th character is p


Javascript!

merlyn on 2005-09-09T14:05:29

Where have you been all my life? Right under my nose! Right here in this browser!

Javascript... giver of pain and pleasure!

Re:

Aristotle on 2005-09-09T16:20:01

It’s actually kind of fun.

The language itself is kind of neat. It has hashes, lists, and closures, so you can easily speak Javascript with a lisp. It sure isn’t Lisp or Perl, but it’s quite tolerable. I’d rather write Javascript than PHP…

And implementations across browsers now have a modicum of consistency, so you don’t pull your hair out all the time.

Re:

Aristotle on 2005-09-09T16:12:47

ord? Don’t you mean chr?

ord does the opposite (take a char, return the codepoint).

Re:

TorgoX on 2005-09-09T20:55:22

Oops

Re:

TorgoX on 2005-09-10T03:56:25

OK, fixed!

ordinal suffix

rjbs on 2005-09-10T01:40:14

I'm a little wracked out right now, but don't you want to mod 10 after mod 100 isn't 11-13? 122, after all, should be 122nd, not 122th.

Re:ordinal suffix

TorgoX on 2005-09-10T03:56:08

Dang, I dropped a line in the pasting! It was there in the original... OK, fixed! Thanks for catching this!