Flash Friday Daryl Ducharme Flash Friday Daryl Ducharme

Repeated string without a loop

ascodeicon.png

A problem comes up

This week I had a relatively simple problem that I needed to solve. Because it was simple and I didn't like the obvious solution, I thought I'd share the solution I came up with.

The problem was this:

  • I had a string where each character represented some data as part of a collection of data.
  • I had to change these characters out of order (for example: character 196, then 13, then 87, etc)

My approach - Create a string of n-length

The approach I decided on was to start by creating a string of the final length I would need then update each character as I got the information I needed. Should be simple enough to create a string of a certain length but alas, not so simple as to have a String.createStringOfLength() method.

The obvious method

My first method of doing this is the obvious loop method. I'm a big fan of loops so it looked like this:

function createStringOfLength(length:uint):String {
    // we'll use 'x' as our default character - spaces are fine too.
    var output:String = "";
    for(var index:uint = 0; index < length; index++){
         output += "x";
    }
    return output;
}

And that function works fine, it is understandable but it just seems that there should be a more elegant solution.

A more elegant solution

The problem with the method above is that I can't just create a string of an arbitrary length but I feel like I should be able to. Is there something else in AS3 that you can create of an arbitrary length? Yes! You can create a Vector of a specific length and use default values to boot.

Here's where it starts to get elegant. Since Strings really are just an array of characters this correlation makes a lot of sense. The code above can actually be recreated in 2 lines (not counting the function definition and enclosing curly braces).

function createStringOfLength(length:uint):String {
     var output:Vector.<uint> = new Vector.<uint>(count, true);
     return output.join("").replace(/0/g, "x");
}

I used a few tricks of the language here, so some of this may not be obvious. First, in AS3, the default value for a uint is 0. That is the reason I search for it in the pattern for the replace call. Second, and really the main thing, I took advantage of the ability to create a Vector of a specified length and fill it with its type (in this case uint) defaults. Finally, I just used the Vector.join method and replaced the default 0 with whatever character I wanted. Admittedly, I could have just left them all as 0 but the replace step was so simple I thought I'd throw it in.

Conclusion

There probably wasn't a performance reason for me to create this solution, and I honestly don't know if it is any more performant. Looking at new ways to relate to a problem is the bread and butter of a programmer though. So, if you've ever wanted to create a string of a specified length or repeat any string a certain number of times here is a new way to think about the problem.

Do you have another solution? If so, I'd love to hear it. Did you like my solution? Hate it? Have an improvement? Let me know in the comments below or share a link to your code. Github's gists are a great way to share code snippets - as I just did right there.

Read More
Flash Friday Daryl Ducharme Flash Friday Daryl Ducharme

Function Overloading in AS3

Why doesn't AS3 have function overloading

If there is anything I hate more than when actionscript doesn't do something I wish it would, it is when people complain about something they wish it would do. Sure, it would be nice if it incorporated every programming concept ever but that just isn't going to happen. In fact, this point is the same for every language out there. It sure would be nice if they all did everything but then there would only be syntacticular differences and that would be silly. Anyway, actionscript does not natively offer function overloading, and I've heard and/or read people complain about that from time to time.

Roll your own

Usually the reason you wish a solution existed natively is because you've used it before and you'd like to have the same ease writing the code. At least, if we follow the premise of not pre-optimizing code. So, if a language doesn't have that construct what do you do? Either find an alternate or roll your own. Today we are going to roll our own method for overloading functions in AS3 to allow for some of the benifits of native function overloading.

This isn't my idea

I have to admit, this isn't my idea. Back in the days of AS2, there was one library that did a lot of rolling its own solutions to constructs actionscript didn't provide. That library was as2lib by Simon Wacker and Martin Heidegger. I remember just reading the as2lib source code to learn different ways of doing thing. They had a solution for function overloading that I used as a basis for the AS3 code. I figured, AS3 had better reflection and introspection (as2lib had libraries for that as well) than AS2 so this should be fairly easy. In some ways it was and in some was it wasn't. That's a good thing because I learned a few things along the way.

Enough typing, where's the code

The code I wrote to allow this functionality is available at github. Usual rules apply, this code is just a proof of concept, for educational purposes only. Though I've written some tests, I make no guarantees.

Sample Usage

Sample usage is available in the Main.as file on github but I'll provide you with a taste here.

private function aFunction(... args):* {
    const overloader:Overloader = new Overloader();
    overloader.addHandler([String, Number], onStringNumber);
    overloader.addHandler([String], onString);
    overloader.addHandler([Number], onNumber);
    overloader.addHandler([int], onInt);
    overloader.addHandler([uint], onUint);
    overloader.addHandler([Boolean], onBoolean);
    return overloader.process(args);
}

private function onInt(value:int):void {
    trace("We got int: " + value);
}

private function onUint(value:uint):void {
    trace("We got uint: " + value);
}

private function onBoolean(value:Boolean):void {
    trace("We got Boolean: " + value);
}

private function onNumber(num:Number):void {
    trace("We got number: " + num);
}

private function onString(str:String):void {
    trace("We got string: " + str);
}

private function onStringNumber(str:String, num:Number):void {
    trace("We got string, number: " + str + ", " + num);
}

// then to use the overloaded function
public funciton Main(){
    aFunction("Hello World", 13); // output: We got string, number: Hello World, 13
    aFunction(1 == 0); // output: We got Boolean: false
    aFunction(13); // output: We got uint: 13
    aFunction("Goodbye"); // output: We got string: Goodbye
}

A couple notes and gotchas that you might be wondering about as you look at this code.

  • Numerical arguments are automatically converted to any numerical class asked for, as long as the value can be of that type.

    • For this reason I made it test numerical explicitness in the following order: uint before int and int before Number.

      • Therefore if their are two matching functions due to numerical parameters a method using uint will be considered more explicit than a method using int or number.
    • You can't force a numerical type. I tried several methods and none worked.
  • If your overloaded function returns void you will need it to return * so it will compile without error.
    • EDIT: not true, just don't use a return statement
  • Because AS3 uses method closures most of the time, instead of anonymous functions, you usually don't have to worry about function scope. This is mostly a good thing. Watch out if you do use an anonymous function though. It will most likely work correct but there are a few ways it could fool you.
  • I wanted to do introspection on the method signatures so you didn't have to send in the values but, alas, method signatures do not seem to be available via reflection. From what I could figure out from studying the Tamarin code, they are part of the functions Trait object which isn't available from actionscript (and may go away in the future according to the documentation). This means you have to put them in as Arrays.

Not True Overloading

Okay, so this isn't true overloading but it gets us a little of the way there. The only solutions available online use the ellipsis (...) method but you still have to write the boilerplate logic to provide type checking. Also, what happens if there is no match? With my code you at least get an error telling you what went wrong. It isn't compile time but it can help with debugging.

Also, look at what this solution actually provides. It doesn't have to be used for function overloading. It could be used anywhere you want to handle differing types of data passed in as arguments. I could envision this helping to trim down some nasty if and/or switch statements. Take a look and see what it could do for you.

Conclusion

I find the Function class and Function objects fascinating in actionscript. Back when I dug into the different types of Delegate classes for AS2 (I actually made a similar one for AS3 at one time) I learned a lot about the language as a whole. Scope used to be the bane of my existence and then I finally understood it. Scope may not be an issue anymore in AS3 but there is still quite a bit to learned about the language from studying Function objects. The very fact that a Function is an object that can be passed around in actionscript is a very nice thing. Not all languages allow that type of functionality. I guess if you are using those, you'll have to roll your own function passing solution.

Read More
Just Another Magic Monday Daryl Ducharme Just Another Magic Monday Daryl Ducharme

Magic Monday: An Ha

This JAMM post takes us to Le Plus Grand Cabaret du Monde with an awesome display of card manipulation by An Ha. The routine starts off pretty standard for card manipulation routines but then moves on. He adds color and rhythm in such a jaw dropping way. By the end he gets a well deserved standing ovation. Many fellow magicians look on with childish grins on their faces.

Two Things about me

Anyone who has been reading my blog for a while knows two things about me. One, I am a francophile. Two, my favorite type of magic is sleight of hand and when it comes to the stage that shows up in card manipulation routines quite often.

Taking care of the francophile who likes magic

France 2 has a show called Le Plus Grand Cabaret du Monde that I've most likely shown at least once before in a JAMM post.

This JAMM post takes us to Le Plus Grand Cabaret du Monde with an awesome display of card manipulation by An Ha. The routine starts off pretty standard for card manipulation routines but then moves on. He adds color and rhythm in such a jaw dropping way. By the end he gets a well deserved standing ovation. Many fellow magicians look on with childish grins on their faces.

[youtube http://www.youtube.com/watch?v=tHjaRbTfHmQ&w=640&h=360]

Conclusion

I hope you've enjoyed this video. Please let me know what you liked or didn't about it. Better yet, join me at JAMM Live coming up this next Wednesday and let me know what you think live.

Read More
Just Another Magic Monday Daryl Ducharme Just Another Magic Monday Daryl Ducharme

Happy Magical Year of the Dragon

Today is the start of the Chinese New Year and the year of the Dragon. Since it is a Monday I thought I'd do a little something special for this week's JAMM post. Since it is a chinese new year I thought I would show a magical way the chinese are bringing in the new year - with Lu Chen. I have showed a performance by Lu Chen before but this is a larger collection of routines put into a great performance that comes across without me understanding anything they are saying. So, without further ado, let's celebrate the New Year with a whole load of magic from Lu Chen.

If you enjoyed this please let me know in the comments below.

Read More
Sunday Funnies Daryl Ducharme Sunday Funnies Daryl Ducharme

Autolycus AKA Bruce Campbell

Used to be, my wife and I would watch Xena, Warrior Princess together on TV. The show, by itself, had some very funny moments. However both Xena and Hercules had a reoccurring character that was quite silly. No, not talking about Ted Raimi's Joxer the Mighty (though I loved him to) but the King of Thieves - Autolycus, played by B as in B-movie (or is that Burn Notice?) Bruce Campbell.

Used to be, my wife and I would watch Xena, Warrior Princess together on TV. The show, by itself, had some very funny moments. However both Xena and Hercules had a reoccurring character that was quite silly. No, not talking about Ted Raimi's Joxer the Mighty (though I loved him too) but the King of Thieves - Autolycus, played by B as in B-movie (or is that Burn Notice?) Bruce Campbell. Inspired by his twitter feed and being in a remembering Xena mood for some reason, I went on a hunt for a humorous video for this week's Sunday Funnies post. I believe this video montage properly shows the smoothness of Autolycus with the humor of one Bruce Campbell.

[youtube http://www.youtube.com/watch?v=a0xjQt1cZ2c?wmode=opaque&w=640&h=480]

I miss the silliness of the characters portrayed in the Xena/Hercules universe and I wouldn't mind seeing them again in new stuff.

Read More
Flash Friday Daryl Ducharme Flash Friday Daryl Ducharme

Quick tip Ctrl+3

There are shortcuts for Flash Builder common features but Project-->Clean... isn't one of them. Eclipse has an interesting Keyboard Shortcut in CTRL+3 - Quick Access. The Quick Access shortcut allows you to hit the shortcut then just start typing the name of the feature you want to use - and there is a big list available to you in Eclipse. A bonus to the Quick Access shortcut is that the last feature you used can be used by hitting return. So to set up a shortcut for Project-->Clean there are just a couple steps.

nomouse1.png

So lately I've been teaching myself how to use the Vim editor. If you know anything about Vim you know it is all about efficiency of keyboard usage. The more I've used Vim, the more I don't want to move my hand to my mouse if I don't have to. It's not that I'm lazy, I just want to challenge myself to be more efficient. If you've been reading my blog lately you may have read about me using embedded fonts via Resource Bundles. One problem I've always had with embedded fonts in Flash Builder is that some builds they work and some they don't. I'm guessing its part of the incremental compilation process because doing a Project-->Clean... seems to fix the problem. It works but then I have to move my hand all the way over to my mouse to make it happen. I needed to find a good keyboard shortcut, for some reason I wanted it to be a default key binding.

Enter CTRL+3

There are shortcuts for Flash Builder common features but Project-->Clean... isn't one of them. Eclipse has an interesting Keyboard Shortcut in CTRL+3 - Quick Access. The Quick Access shortcut allows you to hit the shortcut then just start typing the name of the feature you want to use - and there is a big list available to you in Eclipse. A bonus to the Quick Access shortcut is that the last feature you used can be used by hitting return. So to set up a shortcut for Project-->Clean there are just a couple steps.

  1. Hit Ctrl+3
  2. type 'Clean...' then press enter

Now you can trigger a Project-->Clean... with just Ctrl+3 and Enter. The default for me is to clean all projects and I usually only have one project open at a time so I just enter through that as well.

Really, you can use this with just about any feature you'd like. Once you use it, the feature goes into your Quick Access list. Then its as easy as an arrow up or down (or a few keystrokes to type the action name) to get the feature back to the top of your list and use it.

For me this is one of the hidden gems of Flash Builder. You get this for free for using Eclipse. There's plenty more where that came from too. Are there some hidden gems you use all the time? Please share them in the comments below. Flash Fridays are all about sharing knowledge with the community so that we become better developers.

Read More