Tuesday, April 13, 2010

Escript Framework - lPad & rPad

So I have been following the discussion that started on Impossible Siebel 2.0: Introduction to the ABS Framework, which actually started earlier than that on other siebel blogs, to use the escript prototype feature to create a more robust siebel scripting framework. This got me pretty excited as I think it has a lot of potential for a lot of clients that use extensive script. Jason at Impossible Siebel is in the process of elaborating on defining this but I want to jump right in and start posting about some real world examples that could become part of an eventual library. For instance, since escript does not have an lpad or rpad function, I think those are pretty good starts. These are relevant to strings, so we need to modify the String prototype. Here is the script I came up with:

String.prototype.lPad = function(PadLength, PadChar) {
//Use: String.lPad(Number of Characters, Character to Pad)
//Returns: string with the PadChar appended to the left until the string is PadLength in length
return Array((PadLength + 1) - this.length).join(PadChar)+this;
}
String.prototype.rPad = function(PadLength, PadChar) {
//Use: String.rPad(Number of Characters, Character to Pad)
//Returns: string with the PadChar appended to the right until the string is PadLength in length
return this + Array((PadLength + 1) - this.length).join(PadChar);
}

Usage:
var s = "Short";
var r = s.rPad(10, "_"); // "Short_____"
var l = s.lPad(10, "_"); // "_____Short"

UPDATE: Thanks to commenter Jason who points out a more efficient algorithm. I have updated the original post.

1 comment:

  1. Hi Mik

    I really like this initiative.

    Here is my interpration of the LPad function, you'll probably find that it performs better with longer strings, as it dosnt have to concat the whole string for each iteration.

    String.prototype.lPad = function(l,c){
    return Array((l+1)-this.length).join(c)+this;
    }

    Jason

    ReplyDelete