0
0

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

Posted at

こちらの記事のコードを少し変えて、ジェネリクス型を使って汎用的に[値を変換する関数]を引数にとるメソッドを用いてメソッドチェーンを実現する方法を考えました

class Manipulator<T> {
  public value: T;
  
  constructor(input: T) {
    this.value = input;
  }

  changeValue(fn: (value: T) => T): this {
    this.value = fn(this.value);
    return this;
  }
}

実行例

class Manipulator<T> {
  public value: T;
  
  constructor(input: T) {
    this.value = input;
  }

  changeValue(fn: (value: T) => T): 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 Manipulator<string>("アイウabc")
  .changeValue(kanaToHira) //ひらがな変換
  .changeValue(str => str.toUpperCase()) //大文字変換
  .changeValue(str => str.split('').reverse().join('')) //文字列を逆順にする
  .value
console.log(str);  // "CBAういあ" 
0
0
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
0