mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-01-31 15:27:50 +00:00
43 lines
1.1 KiB
JavaScript
43 lines
1.1 KiB
JavaScript
define(['../lang/isError'], function(isError) {
|
|
|
|
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
|
|
var undefined;
|
|
|
|
/**
|
|
* Attempts to invoke `func`, returning either the result or the caught error
|
|
* object. Any additional arguments are provided to `func` when it is invoked.
|
|
*
|
|
* @static
|
|
* @memberOf _
|
|
* @category Utility
|
|
* @param {*} func The function to attempt.
|
|
* @returns {*} Returns the `func` result or error object.
|
|
* @example
|
|
*
|
|
* // avoid throwing errors for invalid selectors
|
|
* var elements = _.attempt(function(selector) {
|
|
* return document.querySelectorAll(selector);
|
|
* }, '>_>');
|
|
*
|
|
* if (_.isError(elements)) {
|
|
* elements = [];
|
|
* }
|
|
*/
|
|
function attempt() {
|
|
var length = arguments.length,
|
|
func = arguments[0];
|
|
|
|
try {
|
|
var args = Array(length ? length - 1 : 0);
|
|
while (--length > 0) {
|
|
args[length - 1] = arguments[length];
|
|
}
|
|
return func.apply(undefined, args);
|
|
} catch(e) {
|
|
return isError(e) ? e : new Error(e);
|
|
}
|
|
}
|
|
|
|
return attempt;
|
|
});
|