try_then.js (1751B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isFunction = require( '@stdlib/assert/is-function' ); 24 25 26 // MAIN // 27 28 /** 29 * If a function does not throw, returns the function return value; otherwise, returns the return value of a second function `y`. 30 * 31 * @param {Function} x - function to try invoking 32 * @param {Function} y - function to invoke if a function throws 33 * @throws {TypeError} first argument must be a function 34 * @returns {*} the return value of either `x` or `y` 35 * 36 * @example 37 * var randu = require( '@stdlib/random/base/randu' ); 38 * 39 * function x() { 40 * if ( randu() < 0.5 ) { 41 * throw new Error( 'beep' ); 42 * } 43 * return 1.0; 44 * } 45 * 46 * function y() { 47 * return randu(); 48 * } 49 * 50 * var z = trythen( x, y ); 51 * // returns <number> 52 */ 53 function trythen( x, y ) { 54 if ( !isFunction( x ) ) { 55 throw new TypeError( 'invalid argument. First argument must be a function. Value: `'+x+'`.' ); 56 } 57 if ( !isFunction( y ) ) { 58 throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+y+'`.' ); 59 } 60 try { 61 return x(); 62 } catch ( error ) { 63 return y( error ); 64 } 65 } 66 67 68 // EXPORTS // 69 70 module.exports = trythen;