String.format() para ActionScript
Em diversas outras linguagens existe suporte para parsear Strings no formato "{0} aaa {1}", substituindo os índices em chaves por valores passados para a função.
Precisei desta funcionalidade com um "algo a mais" em um projeto - suporte a pluralização. Não coloquei a função dentro de String.prototype para não bagunçar a cabeça de quem for manter meu código.
A função é simples:
Actionscript:
-
public static function format( text:String, values:Array ):String {
-
return values == null || values.length == 0 ? "" : text.replace( new RegExp( "\\{(.*?)\\}", "gi" ), function():String{ return arguments[ 1 ].split( "," ).length == 1 ? values[ arguments[ 1 ] ] : arguments[ 1 ].split( "," )[ parseInt( values[ arguments[ 1 ].split( "," )[ 0 ] ] ) == 1 ? 1 : 2 ]; });
-
}
Ou de uma forma mais legível:
Actionscript:
-
package br.com.dclick.utils
-
{
-
public class StringUtils
-
{
-
private static const REGEXP:RegExp = new RegExp( "\\{(.*?)\\}", "gi" );
-
-
/**
-
* Exemplo:
-
* StringUtils.format( "{0}-{1} de {2} items", [ 1, 20, 1000 ] )
-
* retorna "1-20 de 1000 items".
-
*
-
*
-
* A função também tem suporte simples a pluralização. Se um dos parametros ({x})
-
* se encontra no formato "{posicao com o valor a ser comparado, singular, plural}"
-
* o parsing é realizado.
-
*
-
* Por exemplo, "{0}-{1} de {2} {2,item,items}". O último parâmetro indica que o
-
* parâmetro 2 deve ser comparado. Se for igual a 1, a string "item" é retornada,
-
* caso contrário, a string "items" é retornada.
-
* Portanto,
-
* StringUtils.format( "{0}-{1} de {2} {2,item,items}", [ 1, 20, 1000 ] )
-
* retorna "1-20 de 1000 items. Mas
-
* StringUtils.format( "{0}-{1} de {2} {2,item,items}", [ 1, 1, 1 ] )
-
* retorna "1-1 de 1 item".
-
*
-
* @param text O fomato a ser usado
-
* @param args Os valores para serem substituídos no formato.
-
* @return A string formatada.
-
*
-
*/
-
public static function format( text:String, values:Array ):String
-
{
-
if( values == null || values.length == 0 )
-
return text;
-
-
return text.replace( REGEXP,
-
function():String {
-
// arguments: contem os groups capturados na RegExp. *Ver String.replace()*
-
var split:Array = arguments[ 1 ].split( "," );
-
return split.length == 1
-
// {n}
-
? values[ arguments[ 1 ] ]
-
// {n,s1,s2}, determina plural ou singular
-
: split[ parseInt( values[ split[ 0 ] ] ) == 1 ? 1 : 2 ];
-
});
-
}
-
}
-
}

