File

projects/wms-framework/src/lib/baseframework/StringBuilder.ts

Description

String builder class

Index

Properties
Methods
Accessors

Constructor

constructor(init?: string | number)
Parameters :
Name Type Optional
init string | number Yes

Properties

Private contentIndex
Type : number
Default value : 0
Private contents
Type : string[]

Methods

Public append
append(value: any)

Append a value

Parameters :
Name Type Optional
value any No
Returns : void
Public appendFormat
appendFormat(format: string, ...args: any[])

Appends format

Parameters :
Name Type Optional
format string No
args any[] No
Returns : StringBuilder
Public appendLine
appendLine(value?: string)

Appends line

Parameters :
Name Type Optional
value string Yes
Returns : StringBuilder
Public clear
clear()

Removes all content from the string builder.

Returns : StringBuilder

{StringBuilder}

Public getItem
getItem(index: number)

Gets item by index

Parameters :
Name Type Optional
index number No
Returns : any
Public insert
insert(index: number, value: string)

Inserts the given string into the string builder, at the specified index.

Parameters :
Name Type Optional
index number No
value string No
Returns : StringBuilder

{StringBuilder}

Public remove
remove(start: number, length: number)

Removes a section of the string builder.

Parameters :
Name Type Optional
start number No
length number No
Returns : StringBuilder

{StringBuilder}

Public replace
replace(oldValue: string, newValue: string)

Replace all occurrences of a specified string with another string

Parameters :
Name Type Optional
oldValue string No
newValue string No
Returns : this
Public setItem
setItem(index: number, value: string)

Sets item

Parameters :
Name Type Optional
index number No
value string No
Returns : void
Public toString
toString()

To string

Returns : any

Accessors

length
getlength()

String builder lenght

import { simpleStringFormat } from '../utils/StringFormatting';
import { ArgumentException, ArgumentNullException } from './Exceptions';

/**
 * String comparison enum
 *
 * @export
 * @enum {number}
 * @wEnum System.StringComparison
 * @wNetSupport
 */
export enum StringComparisonKind {
  CurrentCulture,
  CurrentCultureIgnoreCase,
  InvariantCulture,
  InvariantCultureIgnoreCase,
  Ordinal,
  OrdinalIgnoreCase,
}

export function startsWithWithKind(
  str: string,
  strToCheck: string,
  comparisonKind: StringComparisonKind
) {
  switch (comparisonKind) {
    case StringComparisonKind.CurrentCultureIgnoreCase:
    case StringComparisonKind.InvariantCultureIgnoreCase:
    case StringComparisonKind.OrdinalIgnoreCase:
      return str.toUpperCase().startsWith(strToCheck.toUpperCase());
    default:
      return str.startsWith(strToCheck);
  }
}

/**
 * Verifies if the str string ends with the strToCheck string using the StringComparisonKind parameter
 * @param str
 * @param strToCheck
 * @param comparisonKind
 * @returns
 */
export function endsWithWithKind(
  str: string,
  strToCheck: string,
  comparisonKind: StringComparisonKind
) {
  switch (comparisonKind) {
    case StringComparisonKind.CurrentCultureIgnoreCase:
    case StringComparisonKind.InvariantCultureIgnoreCase:
    case StringComparisonKind.OrdinalIgnoreCase:
      return str.toUpperCase().endsWith(strToCheck.toUpperCase());
    default:
      return str.endsWith(strToCheck);
  }
}

export function createStringWithChar(baseString: string, count: number) {
  if (count > 0) {
    const array = new Array(count);
    for (let i = 0; i < count; i++) {
      array[i] = baseString;
    }
    return array.join('');
  } else {
    return baseString;
  }
}

export function removeCharsFromString(
  str: string,
  start: number,
  length?: number
): string {
  if (typeof length === 'undefined') {
    length = str.length;
  }
  return str.substr(0, start) + str.substr(start + length);
}

export function concatStringsSequence(
  separator: string,
  strings: Iterable<any>
): string {
  return [...strings].flat().join(separator);
}

/**
 * Escape regular expression characters from a common string
 *
 * @export
 * @param {string} str string to process
 * @return {*} string  with escaped characters
 */
export function escapeRegexChars(str: string) {
  const regex = new RegExp(
    '((\\\\)|(\\*)|(\\+)|(\\?)|(\\|)|(\\{)|(\\[)|(\\()|(\\))|(\\])|(\\})|(\\^)|(\\.)|(\\$)|#|-|\\s)',
    'g'
  );
  return str.replace(regex, '\\$1');
}

export function stringNullOrWhitespace(str: string) {
  if (str === null || typeof str === 'undefined') {
    return true;
  } else {
    for (let i = 0; i < str.length; i++) {
      if (!(str[i] === ' ' || str[i] === '\t')) {
        return false;
      }
    }
    return true;
  }
}

export function stringTrimLeftChar(str: string, charToTrim: string): string {
  let i = 0;
  for (i = 0; i < str.length; i++) {
    if (str[i] !== charToTrim[0]) {
      break;
    }
  }
  if (i < str.length) {
    return str.substr(i);
  } else if (i === str.length) {
    return '';
  } else {
    return str;
  }
}

/**
 * Removes the specified caracters from the end of the string.
 * If `charToTrim` is a string, removes just `charToTrim[0]` from the end of `str`.
 * If `charToTrim` is an array of strings, removes the first character of every
 * string in the array from the end of `str`.
 *
 * @export
 * @param {string} str
 * @param {(string | string[])} charToTrim
 * @return {*}  {string}
 */
export function stringTrimRightChar(
  str: string,
  charToTrim: string | string[]
): string {
  /* istanbul ignore else */
  if (typeof charToTrim === 'string') {
    charToTrim = [charToTrim];
  }
  /* istanbul ignore else */
  if (!Array.isArray(charToTrim)) {
    throw new Error('charToTrim is not string nor Array');
  }
  const set = new Set(charToTrim.map((x) => x[0]));
  let i = str.length - 1;
  for (; i >= 0; i--) {
    /* istanbul ignore else */
    if (!set.has(str[i])) {
      break;
    }
  }
  return str.slice(0, i + 1);
}

export function stringInsert(
  str: string,
  idx: number,
  strToInsert: string
): string {
  if (idx >= 0 && idx < str.length) {
    return (
      str.substring(0, idx) + strToInsert + str.substr(idx, str.length - idx)
    );
  } else {
    return str;
  }
}

export function stringArraytoRegex(array: string[]): RegExp {
  let regex = new RegExp('(\\[|\\||\\.)', 'g');
  let regexStr = array.map((str) => str.replace(regex, '\\$1')).join('|');
  return new RegExp(regexStr);
}

/**
 * String builder class
 *
 * @export
 * @class StringBuilder
 * @wType System.Text.StringBuilder
 * @wNetSupport
 */
export class StringBuilder {
  private contents: string[];
  private contentIndex: number = 0;
  constructor(init?: string | number) {
    if (typeof init == 'number') {
      this.contents = new Array(init);
      this.contentIndex = 0;
    } else if (typeof init == 'string') {
      this.contentIndex = init.length;
      this.contents = [...init];
    } else {
      this.contents = new Array(16);
      this.contentIndex = 0;
    }
  }

  /**
   * String builder lenght
   *
   * @readonly
   * @memberof StringBuilder
   * @wProperty Length
   */
  public get length() {
    return this.contentIndex;
  }

  /**
   * Gets item by index
   *
   * @param {number} index
   * @returns
   * @memberof StringBuilder
   * @wMethod GetItem
   */
  public getItem(index: number) {
    return this.contents[index];
  }

  /**
   * Sets item
   *
   * @param {number} index
   * @param {string} value
   * @memberof StringBuilder
   * @wMethod SetItem
   */
  public setItem(index: number, value: string) {
    this.contents[index] = value[0];
  }

  /**
   * Appends line
   *
   * @param {string} [value]
   * @returns {StringBuilder}
   * @memberof StringBuilder
   * @wMethod AppendLine
   */
  public appendLine(value?: string): StringBuilder {
    if (typeof value !== 'undefined') {
      this.append(value);
    }
    this.append('\r\n');
    return this;
  }

  /**
   * Append a value
   *
   * @param {*} value
   * @memberof StringBuilder
   * @wMethod Append
   */
  public append(value: any) {
    let str = value?.toString() ?? '';
    if (str && str.length > 0) {
      if (this.contents.length - this.contentIndex >= str.length) {
        let i: number = 0;
        for (i = 0; i < str.length; i++) {
          this.contents[this.contentIndex + i] = str[i];
        }
        this.contentIndex += i;
      } else {
        let newSize =
          str.length +
          this.contents.length +
          Math.trunc(this.contents.length / 2);
        let newContents = new Array(newSize);
        let i = 0;
        for (i = 0; i < this.contents.length; i++) {
          newContents[i] = this.contents[i];
        }
        i = this.contentIndex;
        for (let j = 0; j < str.length; j++) {
          newContents[i] = str[j];
          i++;
        }
        this.contents = newContents;
        this.contentIndex = i;
      }
    }
  }

  /**
   * Appends format
   *
   * @param {string} format
   * @param {...any[]} args
   * @returns {StringBuilder}
   * @memberof StringBuilder
   * @wMethod AppendFormat
   */
  public appendFormat(format: string, ...args: any[]): StringBuilder {
    this.append(simpleStringFormat(format, args));
    return this;
  }

  /**
   * To string
   *
   * @returns
   * @memberof StringBuilder
   * @wMethod ToString
   */
  public toString() {
    return this.contents.join('');
  }

  /**
   * Replace all occurrences of a specified string with another string
   *
   * @param {string} oldValue
   * @param {string} newValue
   * @returns
   * @memberof StringBuilder
   * @wMethod Replace
   */
  public replace(oldValue: string, newValue: string) {
    if (oldValue == null) {
      throw new ArgumentNullException('oldValue');
    } else if (oldValue === '') {
      throw new ArgumentException('Argument oldValue could not be empty.');
    }
    newValue = !newValue ? '' : newValue;
    let newString = this.toString().replace(
      new RegExp(escapeRegexChars(oldValue), 'g'),
      newValue
    );
    this.contents = [...newString];
    this.contentIndex = this.contents.length;
    return this;
  }

  /**
   * Removes a section of the string builder.
   *
   * @param {number} start
   * @param {number} length
   * @return {*}  {StringBuilder}
   * @memberof StringBuilder
   * @wMethod Remove
   */
  public remove(start: number, length: number): StringBuilder {
    /* istanbul ignore else */
    if (start < 0 || length < 0 || start + length > this.length) {
      throw new ArgumentException('Argument out of range');
    }
    this.contents.splice(start, length);
    this.contentIndex -= length;
    return this;
  }

  /**
   * Removes all content from the string builder.
   *
   * @return {*}  {StringBuilder}
   * @memberof StringBuilder
   * @wMethod Clear
   */
  public clear(): StringBuilder {
    this.contents = new Array(16);
    this.contentIndex = 0;
    return this;
  }

  /**
   * Inserts the given string into the string builder, at the specified index.
   *
   * @param {number} index
   * @param {string} value
   * @return {*}  {StringBuilder}
   * @memberof StringBuilder
   * @wMethod Insert
   */
  public insert(index: number, value: string): StringBuilder {
    /* istanbul ignore else */
    if (index < 0 || index > this.length) {
      throw new ArgumentException('Argument out of range');
    }
    /* istanbul ignore else */
    if (value == null || value.length === 0) {
      return this;
    }
    this.contents.splice(index, 0, ...value);
    this.contentIndex += value.length;
    return this;
  }
}

result-matching ""

    No results matching ""