LoginSignup
1
0

More than 1 year has passed since last update.

[Array.prototype拡張] Next.jsで配列からランダムな要素を"シンプル"に取り出す方法

Last updated at Posted at 2023-03-24

はじめに

配列の中からランダムな要素を返すメソッドを、
配列からそのまま呼び出せたら便利そうだと思ったので実装してみました。

イメージ

const arr = ["a","b","c","d"]

// これができると嬉しい
const randomItem = arr.random() // ランダムな要素

拡張を行うファイルを作成

まず、任意のディレクトリ直下に、以下のようなファイルを作成します。
※ 今回はutils直下に作成しています。

// @/utils/__arrayOverride__.ts
Array.prototype.random = function () {
  const length = this.length

  if (length <= 0) return ''

  return this[Math.floor(Math.random() * length)]
}

export {}

拡張ファイルを_app.tsxでimportする

次に、_app.tsxファイルで、先ほど作成したファイルをimportします。

...
// Override
import '@/utils/__arrayOverride__'
...

これにより、アプリケーション全体で配列オブジェクトのprototypeが拡張されます。

型定義を追加

このままだと配列のメソッドに先ほど追加したrandomが表示されないので、型定義を拡張します。

// index.d.ts
declare global {
  interface Array<T> {
    random(): T
  }
}

上記のように、Arrayインターフェースを拡張して、randomメソッドを追加しています。

まとめ

prototypeを拡張する事で、
配列からそのままrandomな要素を返すメソッドにアクセスする事ができるようになるので、
実行箇所でヘルパー関数やMath.randomの呼び出しの必要が無くなり、シンプルなコードで済みます。

これで、"シンプル"に配列からrandomな要素を取り出すことができるようになりました。

参考文献

1
0
2

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
1
0