String.prototype.lengthDecoded = function(){ return (this.length==0 ? 0 : 1 + (this.substring(0,1)=="&" ? this.substring(this.indexOf(";")+1).lengthDecoded() : this.substring(1).lengthDecoded())); }
I'm not convinced I have the best name yet, but in terms of brevity and clarity I think this is a massive improvement over a for loop which will always be in danger of off-by-one errors and simple verbosity.
Here we have what amounts to a single line of code, formatted for clarity that "eats" a string calculating its length as it goes. Simple recursive solutions I'm finding are easier and clearer than their declarative counter-parts. Other than the fact that I'm sitting here writing a blog post about it!
I have considered the idea of creating a subclass of string to do this too, but I'm not convinced the extra complexity that it would bring, and potential to simply not get the correct type in the right place versus using a different function would be better. I could easily make an argument for either.
No comments:
Post a Comment