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

【RV指摘】三項演算子に関するコード

Posted at

三項演算子に関するコードで冗長なコードを書いてしまい、RV指摘を受けたことがあるので備忘です!

いくつかのサンプルを用意したので、
コードを見て、リファクタリングを考えて見てください〜

No.1

  • 元のコード
const isActive = isOnline === true ? true : false;

  • リファクタリング後
const isActive = isOnline === true;
  • 解説
    isOnline === true; が真であれば、true、偽であればfalseということで、冗長な部分はなくすべし。

No.2

  • 元のコード
const isActive = (userAge >= 18) ? true : false;

  • リファクタリング後
const isActive = (userAge >= 18);

No.3

  • 元のコード
    Array.includes を使用した簡略化
const isInList = list.indexOf(item) !== -1 ? true : false;

  • リファクタリング後:
const isInList = list.includes(item);
  • 解説
    indexOf を使って -1 をチェックしてから true / false を返さやり方より、includes メソッドを使えばスッキリ実現可能と。

No.5

  • parseInt の結果をそのまま利用

  • 元のコード:

const parsedValue = parseInt(stringValue, 10) ? parseInt(stringValue, 10) : 0;

  • リファクタリング後:
const parsedValue = parseInt(stringValue, 10) || 0;
  • 解説
    parseInt の結果が NaN の場合、NaN は false として扱われるので、|| 演算子を使って簡潔に書けます。

以上です。

冗長なコードは、無くしていきましょう〜。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?