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?

JavaScriptで条件付きNull変換

Posted at

概要

JavaScriptで任意の値と任意の条件を受け取り、
その値が、前述の条件を満たす際はnullに変換する関数を定義します。
当該条件を満たさない場合は元の値がそのまま返ります。

定義

function mapToNullIf(value, condition = v => false){
    return typeof condition === "function" && condition(value) === true ? null : value;
}

使用例

const x = mapToNullIf(100, v => v > 100);
const y = mapToNullIf(101, v => v > 100);
console.log("x is " + x + ", y is " + y + ".");

表示

x is 100, y is null.
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?