Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby-like Question: Make this function shorter (ActionScript 3)

I just wrote this incredibly verbose code to turn numbers like 2 into 02. Can you make this function shorter, please (maintaning the functionality)?

    public static function format(n:int, minimumLength:int):String {
        var retVal:String = n.toString();
        var stillNeed:int = minimumLength - retVal.length;
        for (var i:int = 0; i < stillNeed; i++) {
            retVal = "0" + retVal;
        }
        return retVal;
    }

Please use types for variables. Extra points (good-vibe points, not SO points) if there's already a built-in function that I don't know about.

If anybody wants to post some extremely short equivalent in some other language, that would be fun too.

like image 752
Dan Rosenstark Avatar asked Dec 01 '22 12:12

Dan Rosenstark


2 Answers

This wouldn't be the fastest implementation (it does some unnecessary copying and has a loop), but it is nice and readable:

public static function pad(num:int, minLength:uint):String {
    var str:String = num.toString();
    while (str.length < minLength) str = "0" + str;
    return str;
}
like image 180
grapefrukt Avatar answered Dec 09 '22 10:12

grapefrukt


I don't think there is a built-in way, but this might be cleaner (if not necessarily better performing):

//20 zeroes, could be more if needed
public static var Zeroes:String = "00000000000000000000"   

public static function format(n:Number, minimumLength:int):String {
var retVal:String = (n.toFixed(0)); // cut off the decimals
var stillNeed:int = minimumLength - retVal.length;
retVal = Zeroes.substring(0, stillNeed) + retVal; 
return retVal;
}

The "zeroes" var eliminates the need for looping, just prepend however many zeroes you need from a prebuilt string.

like image 31
Dave Swersky Avatar answered Dec 09 '22 10:12

Dave Swersky