30秒学会 JavaScript 片段 · 2020年4月6日

30秒学会 JavaScript 片段 – coalesceFactory

Returns a customized coalesce function that returns the first argument that returns true from the provided argument validation function.

Use Array.prototype.find() to return the first argument that returns true from the provided argument validation function.

代码片段

const coalesceFactory = valid => (...args) => args.find(valid);

使用样例

const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));
customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo"