Search code examples
angularangular2-formstypescript1.8

StringBuffer equivalent in typescript


I am trying to convert a Dart pipe to typescript, but there does not seem to be an equivalent of StringBuffer in typescript. The Dart code is shown below

.dart

@Pipe( name: 'titleCase' )
class TitleCasePipe extends PipeTransform {
  dynamic transform( String value, List args ) {
    StringBuffer buffer = new StringBuffer( );

    if ( !isNull( value ) ) {
      List<String> list = value.split( '' );

      if ( value.startsWith( new RegExp( r"^[is]{1,2}([A-Z]|[0-9])" ) ) ) {
        int start = 2;
        List<String> sublist = list.sublist( start );
        return sublist.join( '' );
      }

      for ( int i = 0; i < list.length; i++ ) {
        if ( i == 0 ) {
          buffer.write( list[i].toUpperCase( ) );
          continue;
        }

        if ( isUppercase( list[i] ) ) {
          buffer.write( ' ' );
          buffer.write( list[i] );
          continue;
        }

        buffer.write( list[i] );
      }
    }
    return buffer.toString( );
  }
}

What is the best substitution for String buffer or how best can I convert the pipe using typescript.

Thanks


Solution

  • I would use an array

    @Pipe({ name: 'titleCase'})
    class TitleCasePipe extends PipeTransform {
      transform(value:string, args:any[] ):any {
        buffer:string[] = [];
    
        if ( !isNull( value ) ) {
          list:string[] = value.split( '' );
    
    
          if ( value.match(/^[is]{1,2}([A-Z]|[0-9]).*/ ) ) {
            start:number = 2;
            sublist:string[] = list.slice( start );
            return sublist.join( '' );
          }
    
          for (i = 0; i < list.length; i++ ) {
            if ( i == 0 ) {
              buffer.push( list[i].toUpperCase( ) );
              continue;
            }
    
            if ( isUppercase( list[i] ) ) {
              buffer.push( ' ' );
              buffer.push( list[i] );
              continue;
            }
    
            buffer.push( list[i] );
          }
        }
        return buffer.join('');
      }
    }
    

    (caution - not tested)