🐊Putout plugin helps with maybe
monad.
npm i @putout/plugin-maybe -D
{
"rules": {
"maybe/array": "on",
"maybe/empty-array": "on",
"maybe/fn": "on",
"maybe/noop": "on",
"maybe/declare": "on"
}
}
const {isArray} = Array;
const array = isArray(a) ? a : [a];
const {isArray} = Array;
const maybeArray = (a) => isArray(a) ? a : [a];
const array = maybeArray(a);
const array = !a ? [] : a;
const maybeArray = (a) => !a ? [] : a;
const array = maybeEmptyArray(a);
const isFn = (a) => typeof a === 'function';
const fn = isFn(a) ? a : () => {};
const isFn = (a) => typeof a === 'function';
const noop = () => {};
const maybeFn = isFn(a) ? a : noop;
const fn = maybeFn(a);
const fn = f || (() => {});
const noop = () => {};
const fn = fn || noop;
When you not sure is f
a function, but you want to use it as function anyways:
const fn = maybeFn(f);
const isFn = (a) => typeof a === 'function';
const noop = () => {};
const maybeFn = isFn(a) ? a : noop;
const fn = maybeFn(f);
When you not sure is a
is an array or not, but you want to get first element of it.
const b = maybeFirst(a);
const {isArray} = Array;
const maybeFirst = (a) => isArray(a) ? a[0] : a;
const b = maybeFirst(a);
MIT