воскресенье, 20 марта 2011 г.

String.format - Simpiest, Shortest, Faster

Some hours ago I published article about String.format. After it I made some improvements. And it's 3 types of this function. I think that first most useful becouse weight of code not importent , fastest version show speed only on arrays with 10000 elements.



Simpliest


String.prototype.format = function(values){
var str = this,i;
for(i in values)str = str.replace('%'+i,values[i])
return str;
}

//Using

'Hello, %0!'.format(['World'])

'Hello, %name!'.format({name:'World'})


Shortest


function format(str,values){
for(var i in values)str = str.replace('%'+i,values[i])
return str;
}

//Using

format('Hello, %0!',['World'])

format('Hello, %name!',{name:'World'})


Fastest (only list)


function format(str,values){
var i = values.length;
while(i--)str = str.replace('%'+i,values[i])
return str;
}

//Using

format('Hello, %0!',['World'])

format('Hello, %name!',{name:'World'}) //Not possible

8 коммент.:

  1. Nevermind, i misread. But what about when you have both %foo, and %foobar, sometimes the shorter will overwrite the longer?

    ОтветитьУдалить
  2. function format(str,values){
    for(var i in values) {
    str = str.replace(new RegExp('%'+i+'\\W', 'g'), values[i]);
    }
    return str;
    }

    this will fix the issue that id mentioned.

    However, why not use a format that has a variable delimiter like "I like to {verb}" ? This will allow you to easily and accurately append strings to replacement variables e.g. "I like {animal}s" where "I like %animals" is ambiguous since it could be either `%animal` or `%animals`

    ОтветитьУдалить
  3. wow this is epic, haven't seen something like this that can emulat printf like functions in C

    ОтветитьУдалить
  4. It will probably break if you substitute %1 in at the first place. Something like:

    "hello %0 world %1 whale".format(["%1", "something"]);

    ОтветитьУдалить
  5. @kyle There is actually an sprintf package available for javascript https://github.com/wdavidw/node-printf

    ОтветитьУдалить
  6. Another epic kluge from the epic kluge programming language - Javascript. I personally wish Javascript would crawl away into a corner and die.

    ОтветитьУдалить
  7. String.prototype.format = function()
    {
    var args = arguments;
    return this.replace(/\{\d+\}/g, function(capture){ return args[capture.match(/\d+/)]; });
    }
    use:
    'Hello, {0}!'.format( 'world');

    ОтветитьУдалить