It's a similar pattern that arises in many programming languages - the need for a function to accept differing structures of arguments - and is the reason why certain languages have built-in support for this behaviour, with the use of functional overloading.
In JavaScript however, no such ability exists - and with each of my pure js projects over the last 4 or 5 years, I kept getting rather bored with writing and rewriting the same kind of checks at the top of a function to handle a range of different ways the entity could be called.
So I've been playing with a solution to this idea for a while, but each of my implementations always felt like over coding the issue. JavaScript should be light, quick and powerful - most of what I came up with wasn't.
However, having reached the same situation for the umpteenth time. I finally threw together a solution that seems to be exactly what I've needed, so far at least, and is a lot simpler than previous versions:
var describe = (function(){
var describe = function( obj, opt, mod, looped ){
var m,i,s,t = describe.type(obj), w = describe.type(opt);
if ( w === 'number' || w === 'array' ) {
mod = opt; w = opt = null;
}
if ( describe.type( mod ) == 'number' ) {
m = mod
}
else {
m = describe.TYPES
};
if ( (t === 'array') && (!looped || m & describe.ARRAYS) ) {
s = '';
for ( i in obj ) {
if ( obj.hasOwnProperty && !obj.hasOwnProperty(i) ) {continue;};
s += (s?',':'')
+ describe(obj[i], mod && mod[i] ? mod[i] : m, null, true);
}
t = '['+s+']';
m = null;
}
if ( w === 'object' ) {
if ( opt[t] ) {
opt[t].apply(describe,obj);
}
else if (opt['*']) {
opt['*'].apply(describe,obj);
}
}
else if ( m ) {
s = '';
if ( m & describe.VALUES ) {
s += String(obj);
}
else {
s += (s?':':'') + t;
}
t = s;
}
return t;
}
describe.TYPES = 1;
describe.VALUES = 2;
describe.ARRAYS = 4;
describe.type = function(obj,t){
if (
(t = typeof obj) &&
t === 'string' ||
t === 'number' ||
t === 'boolean' ||
t === 'function' ) {
/// ILB
}
else if ( t == 'undefined' || obj === null ) {
t = 'null';
}
else if(
(t == 'array') ||
(window.Array && obj instanceof Array) ||
(obj.join && obj.slice && obj.unshift) ||
(obj[0] && obj.length) ||
(window.jQuery && obj instanceof jQuery)
){
t = 'array';
}
else if (
(obj.call && obj.apply) ||
(window.Function && obj instanceof Function)
){
t = 'function';
}
else if ( obj.location && obj.open ){
t = 'window';
}
else if ( obj.getElementById ){
t = 'document';
}
else if ( obj.getElementsByTagName ){
t = 'element';
}
return t;
}
return describe;
})();
The idea is a simple one, which could (and will) be improved over time. It's based mainly on type checking, but it can also handle value checking. A basic implementation would be as follows:
var my_function_to_call = function(a,b,c,d){
describe(arguments,{
'[object,object]':function(a,b){
/// do what you need to set-up if you get two objects
},
'[string,object,number]':function(a,b,c){
/// do what you need to set-up given a string, object and a number
}
'*':function(a,b){
/// fallback for anything else
}
});
}
The above makes for much easier reading, and even though this example does create and destroy several temporary functions with each my_function_to_call() -- for most of my core functions that might only get called once or twice it works very well. Obviously you could optimise by keeping your second parameter for describe defined outside of my_function_to_call, but if you are really looking for optimal high-frequency code you should be using the standard js methods of type checking.
A few other ways the code can be used:
var test = function(name, step){
describe(arguments,{
'[helloworld:string,123:number]':function(a,b){
/// do something when specific values and types are passed
},
}, describe.VALUES | describe.TYPES);
describe(arguments,{
'[helloworld,123]':function(a,b){
/// do something when specific values are passed
},
}, describe.VALUES);
describe(arguments,{
'[helloworld,number]':function(a,b){
/// do something when a specific value and specific type is passed
},
}, [describe.VALUES, describe.TYPES]);
}
test('helloworld', 10);
The astute readers out there will notice that this function basically just describes whatever object is passed into it, in simple terms. The secondary parameter is a bonus, as it allows the generated descriptive string to be checked against an object of methods. So you can use the above function just to aid in type checking:
if ( describe(param) == 'array' ) {
/// do something with an array - the code uses a duck test
/// so if something quacks like an array - i.e. jQuery it'll
/// be called an array. I do have another version of this code
/// that is specifically designed to return jQuery for jQuery objs.
}
This is just a starting out point, but so far I like the way things are working, so I shall continue...
Below you will find a minimized version of the above code:
var describe=(function(){var a=function(b,c,d,e){var f,g,h,i=a.type(b),j=a.type(c);
if(j==="number"||j==="array"){d=c;j=c=null}if(a.type(d)=="number"){f=d}
else{f=a.TYPES}if(i==="array"&&(!e||f&a.ARRAYS)){h="";
for(g in b){if(b.hasOwnProperty&&!b.hasOwnProperty(g)){continue}
h+=(h?",":"")+a(b[g],d&&d[g]?d[g]:f,null,true)}i="["+h+"]";f=null}
if(j==="object"){if(c[i]){c[i].apply(a,b)}else if(c["*"]){c["*"].apply(a,b)}}
else if(f){h="";if(f&a.VALUES){h+=String(b)}else{h+=(h?":":"")+i}i=h}
return i};a.TYPES=1;a.VALUES=2;a.ARRAYS=4;a.type=function(a,b){
if((b=typeof a)&&b==="string"||b==="number"||b==="boolean"||b==="function"){}
else if(b=="undefined"||b===null){b="null"}
else if(b=="array"||window.Array&&a instanceof Array||
a.join&&a.slice&&a.unshift||a[0]&&a.length||
window.jQuery&&a instanceof jQuery){b="array"}
else if(a.call&&a.apply||window.Function&&a instanceof Function){b="function"}
else if(a.location&&a.open){b="window"}else if(a.getElementById){b="document"}
else if(a.getElementsByTagName){b="element"}return b};return a})();
- One comment • Category: Coding, JavaScript
- Share on Twitter, Facebook, Delicious, Digg, Reddit
Bug with PHPUnit_Extensions_SeleniumTestCase
by Developer @ pebbl.co.uk on Wednesday, 26 September 2012
Over the last few years I've been constantly surrounded by chatter with regard to Selenium, but had never been in a position to try it out. Yesterday that changed when Tate stated the need to have as near to continous integration as possible with the on-going enhancements to their core website.
So, this has led to lots of interesting learning and reading up on something that has - until now - only really been a buzzword for me :)
Unfortunately my first foray into this area led me straight to a rather annoying bug in a particular PHPUnit extension designed to integrate a PHP script with Selenium. Basically I set about doing what most coders would do when presented with an Object Orientated architecture, I attempted to extend PHPUnit_Extensions_SeleniumTestCase with my own functionality.
Initially everything seemed to work as expected... that is until one of my Selenium tests generated an error. Rather than a helpful error message, my script bugged out with the following unhelpful error:
Argument 5 passed to PHPUnit_Framework_Error::__construct() must be an instance of Exception, array given
On a closer look into the problem it seems that PHPUnit_Framework_Error.php has been upgraded, however the code in PHPUnit_Extensions_SeleniumTestCase.php hasn't.
class PHPUnit_Framework_Error extends Exception
{
/**
* Constructor.
*
* @param string $message
* @param integer $code
* @param string $file
* @param integer $line
* @param Exception $previous
*/
public function __construct($message,
$code,
$file,
$line,
Exception $previous = NULL)
{
parent::__construct($message, $code, $previous);
$this->file = $file;
$this->line = $line;
}
}
The fifth argument has been changed to expect an Exception object, whereas, whenever a new PHPUnit_Framework_Error is called into existence from PHPUnit_SeleniumTestCase.php, you get:
throw new PHPUnit_Framework_Error($buffer,
$e->getCode(),
$e->getFile(),
$e->getLine(),
$e->getTrace());
The last parameter is incorrect, it should be:
throw new PHPUnit_Framework_Error($buffer,
$e->getCode(),
$e->getFile(),
$e->getLine(),
$e);
Or at least changing it to the above fixes the issues I was experiencing, now my code warns about errors correctly. Just in case it's useful to anyone out there :)
Ok, so this isn't a tech post... I just felt the need to complain - please ignore me if you don't give a damn about the environment.
http://www.bbc.co.uk/news/uk-scotland-scotland-business-19708915
If you read the article above, it is written with the view that "isn't this great, a renewable source of energy that will be good for everyone!". But aren't renewables supposed to be produced and used with little or no negative impact to the environment?
From what I've read butanol (and ethanol) still burn producing quite a bit of CO2, true, they burn cleaner that typical petrol (gasoline), but they still produce gases that we are supposed to be cutting down on... and now they've found a never ending way to produce a fuel that pollutes in this way. A fuel that will run on existing car systems, so there will be no reason for peope to change their habits or invest in better alternatives (i.e. hydrogen fuel cells).
How is that good news?
Actually, whether this is good news or not is probably all down to how Tullibardine was already "disposing" of it's by-products... If they were just chucking them into a never-ending bonfire then not much is lost.
I guess we don't really believe in all this CO2 "nonsense" after all, do we...?
It's been a while since I last uttered a word on this here platform. Just so you know, I haven't given up... and I am still working away at Pebbl behind the scenes of this rather lacking yet odd demo site.
On another note though - outside of Pebbl world - I've been focusing quite a bit again on good ol' PHP... I'd manage to escape real PHP work for a little bit, but now it is back with 'a vengeance' and is involving me in all sorts of situations where I need to search through large structures to find small bits of information... Small bits of information that could be anywhere (long story).
To save myself a lot of manual labour - something which computers are supposed to help with - I came up with a nice little function to help me out, hence the reason for the post, and the reason for the Pastie link below:
http://pastie.org/4694918 (found a bug! fixed in the next link)
Yes, it is true... and no I haven't converted Pebbl from a JavaScript game in to a bespoke CMS platform or anything mad... Instead I've decided to modify my Canvas Theory library so that it no longer uses Canvas as it's primary rendering system. Now this might seem a little bit illogical for something that started out as a Canvas & HTML5 experiment, but trust me I know what I'm doing ;) The new off-shoot library will be known as SpriteTheory.
Reasons?
Why? you may ask... well actually you most probably wont, but considering Blogs are a bit pointless if there is no need for explanation I'll ignore that statistical likelihood. The main reason for the change is purely due to optimisation, and also so I can prove wrong those out there who deem Flash (and it's contemporaries) to be extinct.
Most coders who claim Flash to be a dead parrot, and that HTML5 is the saving grace of all, have not tried to recreate what is achievable with Flash in HTML5. They have most probably just bundled together a nice slideshow and said "Hey... what was it we needed Flash for again?"... worryingly, some may not have even got that far and prefer to just mimic statements made by others. The fact of the matter is that Flash does a hell of a lot more that what is possible with pure HTML5 & JS - and it does it a hell of a lot faster. But anyways, before I start going off on one, I'll get to the point. I am not pro any particular technology, I just state what is and isn't possible at the moment (that may change of course). What seems not to be acceptably possible currently is to get good performance when running a sprite system using a full-screen canvas element across all the top browsers.
Excuses...
What...? I hear the non-existent critics expel in chorus. Not fast enough? But what about all the game emulators out on the web... or the 3D demos? Well, it seems that nearly all the emulators I've seen operate on a pixel by pixel basis (or small sprites) and usually on canvas elements with dimensions of about 320x200... tiny. This is not what I wanted for Pebbl, I wanted the full area of the browser to be in-use. And well, any 3D environment I've come across using Canvas is either hardware excelerated (using 3D context) or put together in a very specific and limited way... I wanted Pebbl to be 2D and not limited at all.
After spending some time developing a Canvas specific library, I found that no matter how optimal my code was, the clearRect and drawImage methods of the Canvas Element were taking most of the rendering time. So no matter how good I was with my code, I'd still always be limited by something I couldn't alter. As I said before this may change in the future, we shall see. But after finding this out, and making sure I was using my own "only draw what's needed" and "only clear what's changed" system, I was still finding slow-down after implementing less than half of what I wanted to. I was also finding that the frame-rate was wildly different across each browser. This was not good enough, plus it also seemed a bit pointless, when browsers implement their own redraw system anyway.
Conclusions...
So, after a bit of kicking myself for trying to re-invent the wheel and not going for the more elegant solution in the first place, my new library now works based on old-school absolutely positioned HTML Elements with CSS Transformations and Canvas enhancements. The Sprite interface is nearly almost the same, so I shouldn't have to do to much rewriting, all I have to do is dump most of the Canvas draw stuff, and optimise for dealing with HTML Elements instead. No more redraw problems, or slow-down. My main reason for going down the Canvas route in the first place was because I wanted to have pixel-perfect collisions and pixel affects. Considering most browsers handle the creation of many small Canvas elements with ease, and allow these Elements to be treated like any old DIV Element, I don't need to use a full Canvas "Stage" as-it-were and can instead treat each Sprite that needs the advanced methods as a separate Canvas element.
- Leave your comment • Category: Coding, Game Dev, JavaScript
- Share on Twitter, Facebook, Delicious, Digg, Reddit
Webkit: Canvas and background-size performance problems
by Developer @ pebbl.co.uk on Sunday, 2 October 2011
At last...! I've been searching through my code for Pebbl to try and find a specific Webkit performance drain, focussing mainly on the JavaScript, to see if I was doing anything odd. Due to the nature of Pebbl (being a HTML5 Canvas game) I was assuming that the problem was something that I had introduced in to my js Library CanvasTheory. So - trial and error I went - disabling, enabling, profiling, stepping through the code... nothing I removed or added made a blind bit of difference. It never occured to me (well actually obviously it did eventually) to look at the css style options I was using elsewhere on the page.
The problem I was getting was on this underwater scene. (It's not finished yet, the game is totally in progress). Whenever Chrome or Safari loaded this scene, they would go from 1 frame every 12 milliseconds to 1 every 25 in Safari and 1 every 80!! on Chrome. FireFox handled this page perfectly, not even flinching. The only thing that was different to many other scenes in the game, was that this one uses quite a full on blue background... but what made me completely ignore this fact was that I had other scenes with full graphic backgrounds that gave no problems for any of the browsers.
Eventually I spotted one difference that I hadn't considered. To save rendering time, and to get the browsers to use their routines rather than my s(lowly) javascript code, instead of painting the scene backgrounds in the canvas (clearing and then redrawing every frame) I am setting the background on a div that floats behind the canvas tag. With the canvas tag mainly being transparent it all works as expected. Now this I thought was quite an obvious thing to do. However, In order to render my background image to the right size for the underwater scene (compared to the other scenes) I was using "background-size" set to 100% 100%. The second I removed this styling, Chrome and Safari were back to flying along at a decent speed. It seems, for whatever reason, webkit doesn't cache the resized version of the image. So each time Chrome or Safari had to re-render the background image because my canvas tag had trashed it by drawing on top, it seems that they both had to resample/rescale the image again. Rather ridiculous really... as usual hats off to FireFox for doing what you'd expect.
Unfortunately despite working out what the problem is, I don't really have a nice solution. My only options are to fallback to the old method of stetched background images (an image tag with 100% dimensions) and see if that works differently. Or if that fails, use another canvas tag layered behind my first one and specifically paint the background to the right size. I could create a php script that would render the background image to the right size "on request" but that seems a little overkill for what is essentially a mood setting backdrop.
Yet another thing to be disappointed about in terms of Webkit. Don't get me wrong, I love the fact that Webkit is there for so many people / programs and devices to use. I was blown away slightly the first time i saw Flash Air with it's own built in browser... and I love using my Kindle 2 browsing around whereever I want... But I just keep coming across really obscure bugs and it's winding me up :)
- 2 comments • Category: Coding, Game Dev, JavaScript
- Share on Twitter, Facebook, Delicious, Digg, Reddit
Don't ask me why but I've just finished installing the latest recommend version of Drupal 7. I'd been hearing quite a bit of chatter about it recently (after the initial buzz at the beginning of the year (and after the constant comments on the dev channel the year before that)). So I decided that maybe now would be a good time to see what improvements had been made - In my opinion there was a lot needing to be done from Drupal 6...
Before getting started however I did a little bit of research to see what others were saying, and it seemed unanimous really:
- Drupal 7 is cleaner and more though-out than D6
- Scalability is better, but performance is slightly worse.
- There are a lot of modules that have been ported (D7 promise), but many useful ones are still at alpha/beta stages.
- Module Installation and dashboard are +1 by all
From my point of view it only took me about 30 minutes this morning to get a clean install working using SQLite with my "must have" modules installed (Views,CTools,Panels). Which is far better than my experiences before with D6. I quickly created some new Views (like the new interface for Views!), tied those in to new pages controlled by Panels (Panels is now even more extensive!) exposed via Blocks (Blocks are blocks). I got Drupal's basic search working (I haven't looked in to anything more complicated like FuzzySearch altho I am currently looking in to Google Custom Search). And I then customised the main menu to be as I wanted. So all in all, good, and needed minimal time to look things up. However, I always found this to be the case really with Drupal. It's very quick to put together the large, general bits and pieces of a site... Your time just gets eaten up by editing or fixing the more smaller and specific issues which take forever to find.
Anyway, I haven't had too much time to play around now. Nothing from the code point of view. But so far the admin/front-end is a lot cleaner but totally re-arranged and I will admit to getting a little/lot lost. At least there is the feeling that once I've learned the interface it will be clearer and quicker to navigate than D6. The most annoying thing for me with D6 is that nothing was where I'd expected it to be.. whether that's because non-techy people just have very strange thought processes ;) or D6 just was very strange in itself. So D7 is an improvement... I just expect things in D6 places and haven't found everything yet ;)
So overall... since my check in January it still seemed to me that for use on a large-scale projects things would probably ok as long as you have time for bespoke modules (or you have flexibility with how things need to work), for smaller and personal CMS projects it would definitely be my choice just because it seems far more thought out than anything else out there. The "install module from URL" feature is very nice, but quite why this didn't exist previously I have no idea... it's hardly a new concept or difficult to implement, especially when you have complete control over where and how your module developers upload their contributions. I don't mean to sound negative but much of what I have seen so far in D7 is just common sense, obviously achieving common sense on a large scale project is quite difficult if you don't start out with that premise. So I'd say the "hats off" achievement isn't so much the actual new features I've come across, it's getting them all ready and working in harmony across such an open network... which is what they've achieved.