time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

if_then.js (1748B)


      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 condition is truthy, invokes `x`; otherwise, invokes `y`.
     30 *
     31 * @param {boolean} bool - condition
     32 * @param {Function} x - function to invoke if a condition is truthy
     33 * @param {Function} y - function to invoke if a condition is falsy
     34 * @throws {TypeError} second argument must be a function
     35 * @throws {TypeError} third argument must be a function
     36 * @returns {*} return value of either `x` or `y`
     37 *
     38 * @example
     39 * var randu = require( '@stdlib/random/base/randu' );
     40 *
     41 * function x() {
     42 *     return randu() * 100.0;
     43 * }
     44 *
     45 * function y() {
     46 *     return -1.0 * randu() * 100.0;
     47 * }
     48 *
     49 * var z = ifthen( randu() > 0.5, x, y );
     50 * // returns <number>
     51 */
     52 function ifthen( bool, x, y ) {
     53 	if ( !isFunction( x ) ) {
     54 		throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+x+'`.' );
     55 	}
     56 	if ( !isFunction( y ) ) {
     57 		throw new TypeError( 'invalid argument. Third argument must be a function. Value: `'+y+'`.' );
     58 	}
     59 	if ( bool ) {
     60 		return x();
     61 	}
     62 	return y();
     63 }
     64 
     65 
     66 // EXPORTS //
     67 
     68 module.exports = ifthen;