UNPKG

moltres-utils

Version:
68 lines (55 loc) 1.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _isArray = _interopRequireDefault(require("./isArray")); var _isFunction = _interopRequireDefault(require("./isFunction")); var _isObject = _interopRequireDefault(require("./isObject")); var _nArySpread = _interopRequireDefault(require("./nArySpread")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Defines a function that will invoke the named function if it exists on the * last arg. If the method does not, all args are passed through to the default * function. * * @func * @since v0.1.0 * @category data * @sig defn( * name: string, * defaultFn: (*) => any * ): (...args: any[], last: any) => last[name] ? last[name](...args) : defaultFn(...args) * @param {string} name The name of the method to call if it exists * @param {Function} defaultFn The default function to execute if the named one does not exist on the last arg * @returns {Function} The wrapped function * @example * * const get = defn('get', (prop, value) => value[prop]) * get('a', { a: 'foo' }) //=> 'foo' * * const obj = { * props: { * a: 'bar' * } * get: (prop) => obj.props[prop] * } * get('a', obj) //=> 'bar' */ const defn = (name, defaultFn) => { const arity = defaultFn.length; const override = function override(...args) { if (args.length === 0) { return defaultFn.apply(this); } const obj = args[args.length - 1]; if (!(0, _isArray.default)(obj) && (0, _isObject.default)(obj) && (0, _isFunction.default)(obj[name]) && obj !== this) { return obj[name](...args); } return defaultFn.apply(this, args); }; return (0, _nArySpread.default)(arity, override); }; var _default = defn; exports.default = _default; //# sourceMappingURL=defn.js.map