My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Wednesday, October 08, 2008

JavaScript bits and bops :-)

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


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 =, RegExp[i], String[l < length ? l++ : l - 1]);
return result;

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 :)


nk said...

your replace code is buggy, you mean String.prototye.replace = ... right? (note the lowercase 'r'). Even so, it's still buggy in Safari. However, I really like the technique you are using, which is the Javascript equivalent of Ruby's alias_method_chain.

Andrea Giammarchi said...

Hi Nick, thanks for the Report :)

Honestly, I did not try the code in Safari, assuming it's so simple that it should work without problems everywhere.

I will investigate why you had problem, if you give me more details about version, thank you.

Andrea Giammarchi said...

Nick, it runs properly in Chrome :)