DClick

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:
  1. public static function format( text:String, values:Array ):String {
  2.     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 ]; });
  3. }

Ou de uma forma mais legível:

Actionscript:
  1. package br.com.dclick.utils
  2. {
  3.     public class StringUtils
  4.     {
  5.         private static const REGEXP:RegExp = new RegExp( "\\{(.*?)\\}", "gi" );
  6.        
  7.         /**
  8.          * Exemplo:
  9.          * StringUtils.format( "{0}-{1} de {2} items", [ 1, 20, 1000 ] )
  10.          * retorna "1-20 de 1000 items".
  11.          *
  12.          *
  13.          * A função também tem suporte simples a pluralização. Se um dos parametros ({x})
  14.          * se encontra no formato "{posicao com o valor a ser comparado, singular, plural}"
  15.          * o parsing é realizado.
  16.          *
  17.          * Por exemplo, "{0}-{1} de {2} {2,item,items}". O último parâmetro indica que o
  18.          * parâmetro 2 deve ser comparado. Se for igual a 1, a string "item" é retornada,
  19.          * caso contrário, a string "items" é retornada.
  20.          * Portanto,
  21.          * StringUtils.format( "{0}-{1} de {2} {2,item,items}", [ 1, 20, 1000 ] )
  22.          * retorna "1-20 de 1000 items. Mas
  23.          * StringUtils.format( "{0}-{1} de {2} {2,item,items}", [ 1, 1, 1 ] )
  24.          * retorna "1-1 de 1 item".
  25.          *
  26.          * @param text O fomato a ser usado
  27.          * @param args Os valores para serem substituídos no formato.
  28.          * @return A string formatada.
  29.          *
  30.          */    
  31.         public static function format( text:String, values:Array ):String
  32.         {
  33.             if( values == null || values.length == 0 )
  34.                 return text;
  35.  
  36.             return text.replace( REGEXP,
  37.                     function():String {
  38.                         // arguments: contem os groups capturados na RegExp. *Ver String.replace()*
  39.                         var split:Array = arguments[ 1 ].split( "," );
  40.                         return split.length == 1
  41.                                 // {n}
  42.                                 ? values[ arguments[ 1 ] ]
  43.                                 // {n,s1,s2}, determina plural ou singular
  44.                                 : split[ parseInt( values[ split[ 0 ] ] ) == 1 ? 1 : 2 ];
  45.                     });
  46.         }
  47.     }
  48. }

Por Filipe Sabella em 24/January/2008 | Comentar | Trackback


No Translations

Adicionar comentário

(requerido)
(requerido, não será publicado)