Faster way of writing constructors? - actionscript-3

I have to use a lot of Point constructors, like so :
function setLoc(o:*, loc:Point):void
{
o.x = loc.x;
o.y = loc.y;
}
setLoc(obj1, new Point(25,50));
setLoc(obj2, new Point(13,-5));
setLoc(obj3, new Point(186.5,-23));
...
Is there a way to write these in a more compact way, maybe some macros or compiler tricks ? It is very tedious to have to write "new Point(...)" for such a simple Class. I wish I could do something like :
setLoc(obj1, (25,50));
(I dont want to change setLoc(o,p) to setLoc(o,px,py) but I guess thats the best solution)

You could do this:
setLoc(obj1, {x:25, y:50});
Just change the type of the loc argument to Object:
function setLoc(o:*, loc:Object):void
{
o.x = loc.x;
o.y = loc.y;
}

Related

Is there an alternative way to filter xml elements without the E4X syntax?

I am trying to compile some old actionscript code (part of flash app) to JS using Jangaroo. Jangaroo does not support the E4X syntax and it fails at things like the double-dot operator .. or the brackets filters a.(CONDITION). So I need to rewrite those portions of code using plain ActionScript.
For the double-dot operator, I used the instead the method descendants() but I could not find alternative way to write the brackets filter.
Here is the original code I had:
B = xml..destination.(#id == someId)
I wrote it now:
B = xml.descendants("destination").(#id == someId)
But I still want to remove .(#id == someId).
I am thinking of something like:
if (xml.descendants("destination").attribute("id") == someId)
{
B = xml.descendants("destination")
}
Is this possible?
So here is how I proceeded. I have not tested its functionality, but the compiler passed it.
var destinations:XMLList = null;
for each (var elm in xml.descendants("destination") )
{
if ( elm.attribute("id") == someId )
{
destinations += elm;
}
}

How to Use .as Exported File from PhysicsEditor

The question was here for a long time with bounty and no satisfying solution for me. I erased the first post and am posting instead a question that can be answered quickly with a yes or no so I can proceed with my doings.
If you could answer it really fast before it's deleted by "not a good question". Is using a custom shape from PhysicsEditor to Nape the same as doing it with Box2D? (ofc changing syntax)
If you could then give a look in that link then say it's the same process in Nape that'll be enought thanks.
I ask this because I found the Box2D tutorial easier to follow so far.
public var floor:Body;
floor = new Body(BodyType.STATIC);
var floorShape:PhysicsData = new PhysicsData();
floor.shapes.add(floorShape); // Error: Implicit coercion of a value of type PhysicsData to an unrelated type nape.shape:Shape.
floor.space = space;
Update:
According to a comment on this blog post, it sounds like recent versions of Nape have broken compatibility with the physics editor. Specifically, the graphic and graphicUpdate properties no longer exist on body objects. The solution suggested is to remove references to those properties.
I'm not in a position to be able to test this, but you could try updating the createBody method of your floor class as follows:
public static function createBody(name:String /*,graphic:DisplayObject=null*/):Body {
var xret:BodyPair = lookup(name);
//if(graphic==null) return xret.body.copy();
var ret:Body = xret.body.copy();
//graphic.x = graphic.y = 0;
//graphic.rotation = 0;
//var bounds:Rectangle = graphic.getBounds(graphic);
//var offset:Vec2 = Vec2.get(bounds.x-xret.anchor.x, bounds.y-xret.anchor.y);
//ret.graphic = graphic;
/*
ret.graphicUpdate = function(b:Body):void {
var gp:Vec2 = b.localToWorld(offset);
graphic.x = gp.x;
graphic.y = gp.y;
graphic.rotation = (b.rotation*180/Math.PI)%360;
}
*/
return ret;
}

How to find specific value in a large object in node.js?

Actually I've parsed a website using htmlparser and I would like to find a specific value inside the parsed object, for example, a string "$199", and keep tracking that element(by periodic parsing) to see the value is still "$199" or has changed.
And after some painful stupid searching using my eyes, I found the that string is located at somewhere like this:
price = handler.dom[3].children[3].children[3].children[5].children[1].
children[3].children[3].children[5].children[0].children[0].raw;
So I'd like to know whether there are methods which are less painful? Thanks!
A tree based recursive search would probably be easiest to get the node you're interested in.
I've not used htmlparser and the documentation seems a little thin, so this is just an example to get you started and is not tested:
function getElement(el,val) {
if (el.children && el.children.length > 0) {
for (var i = 0, l = el.children.length; i<l; i++) {
var r = getElement(el.children[i],val);
if (r) return r;
}
} else {
if (el.raw == val) {
return el;
}
}
return null;
}
Call getElement(handler.dom[3],'$199') and it'll go through all the children recursively until it finds an element without an children and then compares it's raw value with '$199'. Note this is a straight comparison, you might want to swap this for a regexp or similar?

Custom sorting function bottleneck

I am trying to sort big array using actionscript 3.
The problem is that i have to use custom sorting function which is painfully slow and leads to flash plugin crash.
Below is a sample code for custom function used to sort array by length of its members:
private function sortByLength():int {
var x:int = arguments[0].length;
var y:int = arguments[1].length;
if (x > y){
return 1;
}else if (x < y){
return -1;
}else{
return 0;
}
}
Which is called like this:
var txt:Array = ["abcde","ab","abc","a"];
txt.sort(sortByLength);
Please advise me how can this be done faster ?
How to change application logic to avoid Flash plugin crashes during sorting ?
try to use strong typing whenever possible, here tell your function that you are waiting two strings.
you could rewrite your function in two way one fastest than the other if you know that all your element are not null:
function sortByLength(a:String, b:String):int {
return a.length-b.length // fastest way not comparison
}
and if you can have null check for it (this one will put null in front of all element):
function sortByLengthWithNull(a:String, b:String):int {
if (a==null) return -1
if (b==null) return 1
return a.length-b.length
}
If you need super-fast sorting, then it might be worthwhile not using an array at all and instead using a linked-list. There are different advantages to each. Primarily, with a linked-list, index-access is slow, while iterating through the list is fast, and linked-lists are not native to AS3 so you'll have to roll your own.
On the upside, you may well be able to use some of Polygonal Labs' code: http://lab.polygonal.de/as3ds/.
Sorting is very, very fast for nearly-sorted data with a linked list, as this article discusses: http://lab.polygonal.de/2007/11/26/data-structures-more-on-linked-lists/.
This solution gives you lots more work, but will eventually give you lots more sort-speed too.
Hope this helps.
-- additional --
I noticed your question in the comments of another answer about "One question however is unanswered - how to perform greedy computations in Flash without hanging it?"
For this, essentially the answer is to break your computation over multiple frames, something like this:
public function sort():void
{
addEventListener(Event.ENTER_FRAME, iterateSort);
}
private function iterateSort():void
{
var time:int = getTimer() + TARGET_MILLISECONDS_PER_FRAME;
var isFinished:Boolean = false;
while (!isFinished && getTimer() < time)
isFinished = continueSort();
if (isFinished)
removeEventListener(Event.ENTER_FRAME, iterateSort);
}
function continueSort():Boolean
{
... implement an 'atom of sort' here, whatever that means ...
}
sortByLength should have two parameters, shouldn't it? I guess that's what you mean by the arguments array...
This looks fine to me, unless arguments is not a local variable, but instead a member variable, and you're just looking at its [0] and [1] elements on each function call. That would at least produce undesired results.

AS3: How to simplify Action Script 3 Code?

Here's a example that I've to use when I want to create a button with mouse-over effect:
this.buttonExample.buttonMode = true;
this.buttonExample.useHandCursor = true;
this.buttonExample.addEventListener(MouseEvent.CLICK,myaction);
I'm new to AS3 - is there any way, to simplify this code like this:
this.buttonExample.buttonMode = true;.useHandCursor = true;.addEventListener(MouseEvent.CLICK,myaction);
why does it not works ?
Its already as simple as it gets. Firstly
this.buttonExample.buttonMode = true;
this.buttonExample.useHandCursor = true;
this.buttonExample.addEventListener(MouseEvent.CLICK,myaction)
is much more readable than
this.buttonExample.buttonMode = true;.useHandCursor = true;.addEventListener(MouseEvent.CLICK,myaction);
Always go for readbility over anything else. And secondly,
this.buttonExample.buttonMode = true;
does not return an object so you can't interact with anything.
If you're using that pattern a lot, you can make a helper function:
public function setAsButton(button:Sprite, clickHandler:Function):void {
button.buttonMode = button.userHandCursor = true;
button.addEventListener(MouseEvent.CLICK, clickHandler);
}
Then call it somewhere:
setAsButton(this.buttonExample, myaction);
If you feel that typing this.buttonExample over and over again is too repetitive, simply assign that object to a variable and use that variable in the rest of the statements:
var b : Button = this.buttonExample;
b.buttonMode = true;
b.useHandCursor = true;
b.addEventListener(...);
As other's have mentioned, there's also the with statement, but it's use is discouraged since it makes the code harder to read, and may lead to weird results:
with (this.buttonExample) {
buttonMode = true;
useHandCursor = true;
addEventListener(...);
}
You can, of course, combine these suggestions with other tricks, like chaining assignments:
var b : Button = this.buttonExample;
b.buttonMode = b.useHandCursor = true;
b.addEventListener(...);
Be very careful to only chain assignments in this way if the assigned value is immutable (e.g. true, false, numbers and strings, but not arrays or most other objects), because the same object will be assigned to all variables on the left side. If the value is immutable this doesn't matter, but if it's mutable you can end up with weird results, like this in this example:
a = b = [ ];
a.push(1);
b.push(2);
trace(a); // outputs 1, 2
trace(b); // also outputs 1, 2
The reason for this result is that a and b both reference the same array, and since arrays are mutable it doesn't matter how you access the object, it will still be changed. a and b don't reference different arrays just because they are different variables.
You may think that you could do something like the following, but it will not work.
// this will NOT work
var b : Button = this.buttonExample;
(b.buttonMode = b.useHandCursor = true).addEventListener(...);
The reason why it works to say b.buttonMode = b.useHandCursor = true, but not to add .addEventListener(...) is that the value of an assignment expression (e.g. b.buttonMode = true) is the value assigned to the left hand side (e.g. true). If you add .addEventListener(...) to that you are essentially saying true.addEventListener(...), which clearly is not what you want. In other words
b.buttonMode = b.useHandCursor = false;
is equivalent to
b.useHandCursor = false;
b.buttonMode = b.useHandCursor;
Which should hopefully also make the caveats mentioned above plain.
you can use the with statement. however I'd not encourage you to do so, since it leads to a lot of ambiguity and unclearness.
also, you can have multiple assignments:
this.buttonExample.buttonMode = this.buttonExample.useHandCursor = true;
this sometimes is useful, but for the sake of readability, you shouldn't overuse it.
greetz
back2dos