概要
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.