LoginSignup
0
1

TypeScriptでメソッドチェーンを使って与えた文字列を次々に変換する方法

Posted at

こちらの記事のコードを少し変えて、[文字列を変換する関数]を引数にとるメソッドを用いてメソッドチェーンを実現する方法を考えました

class StringManipulator {
  private value: string;
  constructor(input: string) {
    this.value = input;
  }
  toString(): string {
    return this.value;
  }
  // [文字列を変換する関数]を引数にとるメソッド
  changeString(fn: (str: string) => string): this {
    this.value = fn(this.value);
    return this;
  }
}

実行例

class StringManipulator {
  private value: string;
  constructor(input: string) {
    this.value = input;
  }
  toString(): string {
    return this.value;
  }
  // [文字列を変換する関数]を引数にとるメソッド
  changeString(fn: (str: string) => string): this {
    this.value = fn(this.value);
    return this;
  }
}

// ひらがな変換
function kanaToHira(str: string): string
{
  return str.replace(/[\u30a1-\u30f6]/g, (s) =>
    String.fromCharCode(s.charCodeAt(0) - 0x60)
  );
}

// 使用例
const str = new StringManipulator("アイウabc")
  .changeString(kanaToHira) //ひらがな変換
  .changeString(str => str.toUpperCase()) //大文字変換
  .changeString(str => str.split('').reverse().join('')) //文字列を逆順にする
  .toString()
console.log(str);  // "CBAういあ" 
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1