JavaScript bits and bops :-)

This post is about a couple of probably useful JavaScript functions, that on daily basis could make our code smarter ;)

String.prototype.Replace


Ok, ok, a prototype into a native constructor is not a good start point, but this one, strings dedicated, is probably one of those "must have" protos, a Replace with multiple inputs, as is for PHP.

String.prototype.Replace = function(replace){return function(RegExp, String){
if(!(RegExp instanceof Array))
RegExp = [RegExp];
if(!(String instanceof Array))
String = [String];
for(var result = this, i = 0, l = 0, index = RegExp.length, length = String.length; i < index; i++)
result = replace.call(result, RegExp[i], String[l < length ? l++ : l - 1]);
return result;
}}(String.prototype.replace);

With above prototype it is possible to search and replace with multiple RegExps and multiple replacements. The proto works as native replace one, but it is possible to perform a replace like this as well:

"abc".Replace([/a/, /b/, /c/], "d"); // ddd
"abc".Replace([/a/, /b/, /c/], ["c", "a", "b"]); // cab
"abc".Replace([/a/, /b/, /c/], ["d", function(){return "e"}]); // dee

Tricky enough?


A meanwhile function pattern


Sometime we need two arguments for a generic callback, but sometime we need to do something between the first argument and the second one.
A common generic example could be a time based callback, where we need to get a start time, to perform an operation, and then an end time.
With a simple pattern like this one:


function meanWhile(before, after){
if(2 < arguments.length)
after = arguments[arguments.length - 1];
// do stuff ... return other stuff
return after - before;
};

We are able to execute a couple of interesting operations.
A timing example is this one:

function bigLoop(){
for(var i = 0, max = arguments[0] || 1000000; i < max; i++);
};
meanWhile(new Date, bigLoop(), new Date); // 180 or less if your PC is faster
meanWhile(new Date, bigLoop(), bigLoop(), new Date); // 360 or less ...

Can you imagine better applications?

P.S. It's long time I do not post guys, sorry but it's really a busy period :)

Comments

Popular posts from this blog

8 Things you should not be afraid of as a Developer

News

Why REST is so important