1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

配列から undefined を簡単に除外する、カスタム関数 array.isEmpty() の作り方

Last updated at Posted at 2024-12-07

はじめに

こんにちは、エンジニアのkeitaMaxです。

JavaScriptでarray.map()などのArrayMethodがあると思うのですが、これをカスタムしてarray.isEmpty()というのを作成してみます。

やりたいこと

配列が[][undefined,undefined,undefined]となっている時にarray.isEmpty()をよんでtrueにして、それ以外はfalseにするようなものを作成しようとおもます。

実装

array-extention
└─ src
  ├─ index.ts
  └─ rules
     └─ isEmpty.ts

というようなフォルダ構成にしました。

index.tsで作成したカスタム関数を使用できるようにしようと思います。

isEmpty.tsは以下のように実装しました。

isEmpty.ts
declare global {
  interface Array<T> {
    isEmpty(): boolean;
  }
}

Array.prototype.isEmpty = function (): boolean {
  return this.every(item => item === undefined) || this.length === 0;
}

export { }
declare global {
  interface Array<T> {
    isEmpty(): boolean;
  }
}

この部分で配列型に今回作成した新しいメソッドisEmptyをグローバルに追加しています。

Array.prototype.isEmpty = function (): boolean {
  return this.every(item => item === undefined) || this.length === 0;
}

この部分で実際にすべてがundefinedだった時、もしくはから配列の時にtrueを返すように実装しています。

export { }

グローバルスコープを拡張するために、そのファイルを「モジュール」として認識させるために書いてます。

index.tsは以下のようにimportして拡張した関数を使用できるようにしました。

index.ts
import "./rules/isEmpty"

確かめる

index.tsに以下のコードを書いてエラーが起きないかどうか確認してみます。

index.ts
import "./rules/isEmpty";

const array = [undefined, undefined, undefined]
const result = array.isEmpty()

無事エラーは出なかったです。

おわりに

この記事での質問や、間違っている、もっといい方法があるといったご意見などありましたらご指摘していただけると幸いです。

最後まで読んでいただきありがとうございました!

次の記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?