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)

Friday September 09, 2005
12:01 AM

Adding JavaScript methods to Number

[ #26655 ]
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

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.
  • Where have you been all my life? Right under my nose! Right here in this browser!

    Javascript... giver of pain and pleasure!

    --
    • Randal L. Schwartz
    • Stonehenge
    • 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.

  • ord? Don’t you mean chr?

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

  • 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.
    --
    rjbs