🐊Putout plugin helps with maybe monad.
npm i @putout/plugin-maybe -D
- ✅ array;
- ✅ empty-array;
- ✅ fn;
- ✅ noop;
- ✅ declare;
{
"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;Declares:
- ✅
maybeArray; - ✅
maybeEmptyArray; - ✅
maybeArrayFrom; - ✅
maybeFn; - ✅
maybeFirst; - ✅
maybeCall;
When you not sure is f a function, but you want to use it as function anyways:
const fn = maybeFn(f);
maybeCall(fn);const isFn = (a) => typeof a === 'function';
const noop = () => {};
const maybeFn = (a) => isFn(a) ? a : noop;
const maybeCall = (a, ...b) => isFn(a) && a(...b);
const fn = maybeFn(f);
maybeCall(fn);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