describe.js v0.4, 0.5 and 0.6 have all been, urm... skipped.

by Developer @ pebbl.co.uk on Saturday, 27 April 2013

Things have gone a little quiet on the describe.js front, and the reason for this is that the last three versions have failed to be finished, and so, have also failed to see the light of day. Mainly because I kept on coming up with better ideas, well at least according to my brain anyway.

So just to keep things going — until I actually post some code — I thought I'd report that I'm now working on version 0.7. There is a reason for these leaps, which I'll explain once I'm done, but it should mean that describe will be even more powerful and extensible than before.

You'll just have to take my word for it for the moment though.

JavaScript : Simple RegExp wrapper called ExpReg

by Developer @ pebbl.co.uk

I just put this miniature library together to help work with Regular Expressions in a cleaner and abstracted manner. It's pretty simple, but RegExp interaction in JavaScript has always been a little clunky in my opinion, so it doesn't take much to smooth things out a little.

/// example usage
var result = 
  ExpReg(/\|/gi)
    .haystack('[believe|dont]|[either,way]')
    .replace(function(match, i){return '{'+i+'}';})
    .haystack()
;
/// result = '[believe{8}dont]{14}[either,way]'

Whilst the above may actually be shorter to type in pure JavaScript:

String('[believe|dont]|[either,way]')
  .replace(/\|?(\[[^\]]+\])/gi, function(match, i){
    return '{'+i+'}';
  })
;

.. the problem with the above is that it is completely different from the formation to step through items matched, for example:

var m, re = /\|?(\[[^\]]+\])/gi;
while( (m = re.exec('[believe|dont]|[either,way]')) ) {
  /// do whatever processing required here.
};

The main benefit of using ExpReg would be that the way of dealing with Regular Expressions is standardised, and all the RegExp objects that are created are remembered, so you can refer back to them quickly — useful in code that reuses expressions. Plus it's easy to add new methods that work in a builder fashion — similar to jQuery.

/// another example using a string instead of literal RegExp
ExpReg('/./gi')
  .haystack('this should match every letter')
  .each(function(match, i){alert(i)})
;

/// an example of mapping
var words = 
  ExpReg(/\w+/gi)
    .haystack('this should match every word')
    .map(function(match){return match})
;

Just in case it comes in useful, here is the recently imagined source code of expreg.js :)

/**
 * ExpReg 0.1
 *
 *  ExpReg is just a simple RegExp wrapper that has some useful 
 *  functions for dealing with Regular Expressions. This include 
 *  is designed to work with require.js but can also operate as 
 *  a normal js include.
 *
 *  @author Phil Glanville - 2013/05
 */
var ExpReg;
/// define not-exist fallback
(typeof define === 'undefined' && 
  (define=function(a){return (ExpReg = a())}));
/// hook into require.js
define(function(){
  "use strict";
  var global = {
    delims: new RegExp('^([^a-z0-9\s])(.+?)\\1([gimy]{0,4})$','i'),
    lookup: {}
  };
  /**
   * The outer wrapping constructor that will be exposed as ExpReg
   */
  var ExpReg = function(re, haystack){
    var t;
    if ( this instanceof ExpReg ) {
      if ( !global.lookup[re] ) {
        if ( re instanceof RegExp ) {
          global.lookup[re] = re;
        }
        else if ( (t = global.delims.exec(re)) ) {
          global.lookup[re] = new RegExp(t[2],t[3]);
        }
      }
      this.exp = global.lookup[re];
      this.source = haystack?haystack:'';
      this.matches = [];
      this.matched = false;
      this.reversed = false;
    }
    else {
      if ( typeof this == 'string' ) {
        return new ExpReg(re, ''+this);
      }
      else {
        return new ExpReg(re, haystack);
      }
    }
  };
  /**
   * Simple jQuery like attr function
   */
  ExpReg.prototype.attr = function( name, value ){
    if ( arguments.length == 2 ) {
      this.exp[name] = value;
    }
    else {
      return this.exp[name];
    }
  };
  /**
   * Define the haystack that the RegExp will search
   */
  ExpReg.prototype.haystack = function(string){
    if ( arguments.length && (typeof string == 'string') ) {
      this.source = string;
      this.matched = false;
      return this;
    }
    else {
      return this.source;
    }
  };
  /**
   * Return a particular matched item. A matched item will
   * be an object that contains a zero-indexed array of .groups 
   * and an .offset property that gives the start of where the 
   * match was found.
   */
  ExpReg.prototype.item = function(n){
    if ( arguments.length == 0 || n === undefined || n === null ) {
      return this.matches;
    }
    else if ( n < 0 ) {
      return this.matches[this.matches.length+n];
    }
    else if ( n < this.matches.length ) {
      return this.matches[n];
    }
    else {
      return null;
    }
  };
  /**
   *
   */
  ExpReg.prototype.findAll = function(){
    /// remove previously found items
    this.matches.length = 0;
    /// reset and scan
    var groups; this.exp.lastIndex = 0;
    /// if we are global we can findAll
    if ( this.exp.global ) {
      while( (groups = this.exp.exec(this.source)) ) {
        this.matches[this.matches.length] = {
          groups: groups,
          offset: this.exp.lastIndex-groups[0].length
        };
      }
    }
    /// if not global, match the first and stop
    else {
      this.matches[this.matches.length] = {
        groups: (groups = this.exp.exec(this.source)),
        offset: this.exp.lastIndex-groups[0].length
      };
    }
    ///
    this.matched = true;
  };
  /**
   * Replace current selection with either string or result of callback
   */
  ExpReg.prototype.replace = function(param){
    if ( !this.matched ) { this.findAll(); }
    if ( this.matches.length ) {
      if ( typeof param == 'string' ) {
        this.source = this.source.replace(this.exp, param);
      }
      else if ( param.call ) {
        var exrg = this;
        this.source = this.source
          .replace(this.exp, function(a,b){return param(a,b,exrg)});
      }
    }
    return this;
  };
  /**
   * Call a callback for each match found
   */
  ExpReg.prototype.each = function(callback){
    if ( !this.matched ) { this.findAll(); }
    if ( this.matches.length ) {
      var i, l = this.matches.length;
      for( i = 0; i < l; i++ ) {
        callback.call(this, this.matches[i], i, this);
      }
    }
    return this;
  };
  /**
   * Map the matches to an array
   */
  ExpReg.prototype.map = function(callback){
    var a = [];
    if ( !this.matched ) { this.findAll(); }
    if ( this.matches.length ) {
      var i, l = this.matches.length;
      if( typeof callback == 'undefined' ) { callback = 1; }
      if ( callback.call ) { 
        for( i = 0; i < l; i++ ) {
          a[i] = callback.call(this, this.matches[i], i, this);
        }
      }
      else {
        for( i = 0; i < l; i++ ) {
          if ( this.matches[i] && 
               typeof this.matches[i].groups[callback] != 'undefined' ){
            a[i] = this.matches[i].groups[callback];
          }
        }
      }
    }
    return a;
  };
  /**
   * wrap the matches with strings
   */
  ExpReg.prototype.wrap = function(pre, post){
    this.replace(function(match){
      return pre+match+post;
    });
    return this;
  };
  ExpReg.prototype.reverse = function(){
    if ( !this.matched ) { this.findAll(); }
    this.matches.reverse();
    this.reversed = !this.reversed;
    return this;
  };
  /**
   * debug log
   */
  ExpReg.prototype.log = function(pre, post){
    this.each(function(match, i){
      console.log(i, match);
    });
    return this;
  };
  String.prototype.ExpReg = ExpReg;
  return ExpReg;
});
/// remove our temporary define fallback
(ExpReg) && (define = undefined);

Centre Image : The strange combination of position absolute, margin auto and an image tag

by Developer @ pebbl.co.uk on Thursday, 25 April 2013

Just recently I was charged with the task of upgrading the Slideshow ability on the Tate's website, basically finishing off the work so that it could display more than just images, and to finalise it's mobile support. Most of the work was quite straightforward and entailed reverting some of the previous bespoke modifications made to the default Flexslider plugin, and then enhancing the out-of-the-box functionality with things like full-screen mode, and managing audio or video files that might be contained within.

Stop it and tidy up

One of the main improvements I made was to try and get things working with as little JavaScript as possible, this meant refactoring the CSS somewhat, and due to not having worked closely with CSS for the last year — save for the odd stackoverflow answer — I was quickly reminded just how frustrating-a-language CSS is to debug and repair... especially in it's pure form, outside of any compilation framework like LESS.

Anyway, re-realisations aside, I got pretty much everything working via CSS save for two issues. The first of these problems was the age old annoyance of how to centre an element in the middle of a container on both the vertical and the horizontal. Now I've been using CSS since the early days — if you could refer to them as early — so I'm quite aware of the different vertical alignment tricks that can be employed. I was also aware that the only way(s) I knew of to get an element of unknown or variable dimensions to centre was either to use a table, display:table, or use a background-image instead (at least for images anyway). Any one of these would have taken some crowbarring to get working harmoniously with the slideshow system. Unfortunately, every one of my slideshow images had variable dimensions, which not only varied depending on itself, but was also responsive to the display size... so I had to find some nicer way of doing it.

Solution?

Considering the fact that the well known browsers are now developing at a rate of knots, I decided that there must be a better way by now. Obviously I could have used flexbox, but it's fluctuating and unreliable support would have meant more headaches in testing than I had time for. So I spent quite a bit of time searching around, finding pretty much all the ways I already knew about, until I stumbled upon this random suggestion:

img { position:absolute; left:0;top:0;right:0;bottom:0; margin:auto; }

At first glance that snippet made no sense to me, and I almost automatically dismissed it as nonsense. I'm quite glad I ignored my first thoughts however and tested it out, because — at least for every user agent I checked — it did exactly what I needed. Now, if anyone can explain why this has been built in, and why images should behave differently to any other element, I'd be interested to hear... until then I'll just mark it down to another strange oddity in the interpretation of the rather wholly strange language/construct that is CSS.

Internet Explorer Detection : The power of conditional comments but via jQuery

by Developer @ pebbl.co.uk on Wednesday, 24 April 2013

I came across a situation the other day where I needed a specific browser check (IE7 or less), there wasn't a particular testable feature to hand that would do and I didn't have access to the markup. My usual fix for Internet Explorer specific bugs is to use conditional comments, they do exactly what it says on the tin, however.. not having access to the page markup thwarted this otherwise quick and easy solution.

Rather than falling back to tenuous agent string checking — particularly worrying when it comes to specific version number checks — or bashing my head against multiple feature tests that could be invalidated in the future, I thought the following implementation would be no less mad, and maybe even slightly useful:

var isOldIE = function(query){
  return $('<!--['+(query||'if lte IE 7')+']>OLDIE<![endif]-->')
    .text() === 'OLDIE'
  ;
}

Make of it what you will, but I rather like it... even though it is hideous from an optimisation point of view.

describe.js - v0.4 (ish)

by Developer @ pebbl.co.uk on Sunday, 17 February 2013

After having a bit of time off to wander around Thailand, and finding that — despite having lovely people, beaches, street food, temples and sea life — that the country is drowning in vehicles and unwalkable roads.. this meant there were a few days of relaxing near my laptop. So I took the time to code in the sun and do some extra work with describe.js. In doing so I notice a few problems, which I've now tried to rectify.

  1. Collections only worked for constructors with one method, the foolish mistake of relying on a variable referenced from within a loop.
  2. The 'private' tag was working based on the constructor, so each instance of a constructor was sharing the same private object. Doh!
  3. The 'private' methods were attached (as wanted) to the ._ object, however this meant that 'this' inside a private method refered to the _ object, rather than the constructed instance.

So, I have now repaired these issues, which should definitely speed up development in my other projects. At the same time I've also added a few extra abilities:

  1. Getters and Setters — two new tags exists by default, get and set. These utilise the __defineGetter__ and __defineSetter__ methods, if the browser supports them. The upshot of this is that you can now create getter and setter attributes, that also support type overloading.
  2. Improved support for merging or wrapping functions — This was a byproduct of the fixes. There are now the following methods: merge, unmerge, wrap and unwrap.
  3. Rewrote the tag/plugin handling — this was mainly to fix the private issues above, but now gives the coder a choice to implement a tag/plugin method on the constructor or on the instance (the choice is made by creating a tag function of either 3 or 4 arguments). Implemented on the constructor the prototype object is used (saving resources), implemented on the instance (all private methods use this) the methods are specifically applied to the instance's private object.
  4. I've worked out many of the bugs with regards to properties (before describe only concerned itself with methods). So, now it is possible to create constructors with simple base type attributes... rather silly not to be able to support this in the first place.

Before I go...

I say 0.4ish because there is one major issue that I still hope to fix before uploading the new version, this is the good old multiple inheritance system. This will be the fourth rewrite of this particular bit of code, it's complicated, but I hope to simplify things and stop trying to be so clever (mainly because clever always causes issues unless you've managed to discover perfection lying around somewhere).

I think I'm going to go the same way as a number of other libraries and just use a shallow copy system for the inheritance, rather than relying on a dynamically morphing prototype chain. The reason for this is that I seem to be using the prototype chain more and more with my work in other projects, and the current system is getting in the way. I generally don't need the power of inheritance anyway, just the power of mixins, which is what a shallow copy system would provide.

I guess what I'm saying is there will be an update shortly... so watch the skies, or something.

Oh, a few more other improvements that are in the pipe line:

  1. Collections don't support Getters and Setters, but they will do.
  2. Also, I need to work out a way of describing tag behaviour when using multiple tags. For example, currently specifying 'private get methodName' or 'private set methodName' does not create a private getter or setter. Instead it creates a private method called methodName and a public getter/setter called methodName too.

HMRC — tales of the expected.

by Developer @ pebbl.co.uk on Wednesday, 16 January 2013

Ok, so the title is rather the opposite of self-explanatory, put simply this post is just a complaint really, it has no technical content—I'm still just baffled as to why I expected anything different...

Just recently, due to hitting the VAT threshold as a self-employed web something or other, I had to—yet again—open communications with the creaking bureaucracy that is the HMRC.

When is a website not a website?

My first port of call was obviously their website, which, to anyone—well at least anyone who has the slightest semblance of what good design, good content and good navigation should be—is always a disappointing, if not aggravating experience. Especially if you know how much money it cost to build.

Do not try and find anything specific on hmrc.gov.uk, you'll waste more than just time. I was hunting around for information with regard to already being set up in business, but needing to become VAT registered (probably one of the most common requests). I just ended up following link after link, trying to piece together the little bits of useful snippets dispersed amongst the backdrop of much repetition and information about rare scenarios.

Within at least the first few seconds of landing on the "Introduction to VAT" page and navigating around you'll be hit with hundreds of blocks of bullet points and more "if statements" than a popular JavaScript library would contain. After reading through and working out what seemed to be where I needed to go, I just ended up with dead-end paths... an example of this is the option to register for VAT Online. Sounds great, until you get to the "What you'll need" section, where it states you need a VAT Number! (so not what you actually think it is then). Even if you try and actually get to the Online VAT system (to hell with the VAT Number), I found I just jumped from anchor, to page, to anchor again... the destination just wasn't to be found.

Skip to the end...

So, after much bounding around, I finally decided that I'd send my registration via post—as I managed to find the seemingly correct form (that would actually open on my MacBook)—besides their phone line was consistently busy anyway. I'd also been burnt before by signing up for Government services over the phone only to be told that the conversation never took place. With post, the good thing is, you can make a hardcopy.

So, after a few over-the-top questions, and a few first-class stamps, I had my form filled out and posted. Then I waited...

and waited...

and waited...

An entire two months went by with nothing back. So I called up, and after a while of more costly waiting, I got through to a lady who could hardly tell me anything about my own registration — all in the name of security. Despite me being able to tell her everything that she could ask for, and that there isn't really anything that needs to be kept secure. How could knowing someone has applied for VAT registration be useful in any way? In the end all I could find out was that it was being processed and that my certificate would be sent out to me by second class post; which could take two weeks to reach me.

So I waited...

and waited...

Two weeks later and still nothing. So I called up again, and again could be told nothing about my registration. This time it wasn't even possible to confirm if the original certificate had been sent out... the only option offered was for the certificate to be resent (although this choice of language gave the game away). I wasn't able to pay for a courier or even a first-class stamp, nor could they email the original email address I registered with to notify me of the certificate being posted. All in all rather pathetic, and as usual way behind the services and abilities that the business world offers — yet further annoying fodder for those pesky Conservatives to argue for privatising everything.

And finally.

At time of writing I'm still waiting and am having to write Pro forma invoices, which will have to be followed up with a VAT invoice when I finally get the simple 9 characters that all this has been in aid of. The simple 9 characters that could have been sent to me securely, electronically, and not to mention — in an instant.

This world is in the state it is in due to a large number of people doing jobs that are obviously not worth doing... because they don't do them well. Namely the people who set these services up, and whose job it is to keep things improving and progressing inline with technical ability.

And before I get lynched by those who will correctly say keeping real life up-to-date to the cutting-edge is an expensive way to exist; and should not be the first goal of government or a publicly run service... surely, at the very least, we should be allowed to request a first class stamp?

They've been around a while and I'm quite sure they've been thoroughly tested, perhaps we're still waiting on the results of a royal mail feasibility study.

</rant>

describe.js - v0.3

by Developer @ pebbl.co.uk

Just a quick update to say that describe.js—whilst still supporting type-based method overloading—now supports a few extra abilities:


  1. You can now define optional parameters using tilde ~
  2. You can now create collections for constructors built by describe.make

Collections

Creating a collection is as easy as the following:


var Example = describe.make({
  'method': function(){
    alert(123);
  }
});

var collection = new Example.collection();
    collection.push( new Example() );
    collection.push( new Example() );
    collection.push( new Example() );

collection.method(); /// this will trigger alert(123) three times


This is only the basic collection implementation that I wanted to build, I need to extend the collection manipulation methods i.e. allowing for merging, filtering or collecting collections, plus I have a few more useful ideas in this regard.


Optional parameters

Optional parameters have now been reinstated, and can be implemented in the following ways:


var Example = describe.make({
  'methodA [string,~number]': function(str,num){
    console.log(arguments);
  },
  'methodB [string,number]|[string]': function(str,num){
    console.log(arguments);
  },
  'methodC [string,~number,number]': function(str,n1,n2){
    console.log(arguments);
  },
  'methodD [string,~number,~number]': function(str,n1,n2){
    console.log(arguments);
  }
});

Using [string,~number] is identical to [string,number]|[string] which is identical to creating two methods with the same name (but with differing type arguments) which execute the same function.


The difference between 'methodC [string,~number,number]' and 'methodD [string,~number,~number]' is that the following method lookups will be created inside the constructor:


/**
 * [string,~number,number] will generate:
 * 
 *   [string]
 *   [string,number,number]
 * 
 * [string,~number,~number] will generate:
 * 
 *   [string]
 *   [string,number]
 *   [string,number,number]
 */


Next steps?

I'd like to implement a few more functional "tags" that will take advantage of the new getter and setter implementations, and just generally focus on constructor properties rather than methods, as I haven't really looked at supporting them yet.


var Example = describe.make({
  'set hello': function(v){
    this._.hello = v;
  },
  'get hello': function(){
    return this._.hello;
  }
});

var a = new Example();
    a.hello = 'world';


Other tag ideas...

once

A tag that assigns a method to a constructor, but once called, the method is removed.

event

Tags every method that is used as an event listener, allowing your own code to step in and modify the event object before being used by your constructor code.

moz, opera, webkit, ms

Only assigns the method if the browser is a particular type.