if_else_async.js (2247B)
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 predicate function returns a truthy value, returns `x`; otherwise, returns `y`. 30 * 31 * @param {Function} predicate - predicate function 32 * @param {*} x - value to return if a condition is truthy 33 * @param {*} y - value to return if a condition is falsy 34 * @param {Function} done - callback to invoke upon completion 35 * @throws {TypeError} first argument must be a function 36 * @throws {TypeError} last argument must be a function 37 * 38 * @example 39 * var randu = require( '@stdlib/random/base/randu' ); 40 * 41 * function predicate( clbk ) { 42 * setTimeout( onTimeout, 0 ); 43 * function onTimeout() { 44 * clbk( null, randu() > 0.5 ); 45 * } 46 * } 47 * 48 * function done( error, result ) { 49 * if ( error ) { 50 * throw error; 51 * } 52 * console.log( result ); 53 * } 54 * ifelseAsync( predicate, 1.0, -1.0, done ); 55 */ 56 function ifelseAsync( predicate, x, y, done ) { 57 if ( !isFunction( predicate ) ) { 58 throw new TypeError( 'invalid argument. First argument must be a function. Value: `'+predicate+'`.' ); 59 } 60 if ( !isFunction( done ) ) { 61 throw new TypeError( 'invalid argument. Last argument must be a function. Value: `'+done+'`.' ); 62 } 63 predicate( clbk ); 64 65 /** 66 * Callback invoked by a predicate function. 67 * 68 * @private 69 * @param {(Error|null)} error - error object 70 * @param {boolean} bool - condition 71 * @returns {void} 72 */ 73 function clbk( error, bool ) { 74 if ( error ) { 75 return done( error ); 76 } 77 if ( bool ) { 78 return done( null, x ); 79 } 80 done( null, y ); 81 } 82 } 83 84 85 // EXPORTS // 86 87 module.exports = ifelseAsync;