main.js (2295B)
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 objectKeys = require( '@stdlib/utils/keys' ); 24 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 25 var PROMOTION_RULES = require( './promotion_rules.json' ); 26 27 28 // FUNCTIONS // 29 30 /** 31 * Generates a full table of promotion rules. 32 * 33 * @private 34 * @returns {Object} table 35 */ 36 function generateFullTable() { 37 var dtypes; 38 var ntypes; 39 var out; 40 var tmp; 41 var dt1; 42 var dt2; 43 var o; 44 var j; 45 var i; 46 47 out = {}; 48 dtypes = objectKeys( PROMOTION_RULES ); 49 ntypes = dtypes.length; 50 for ( i = 0; i < ntypes; i++ ) { 51 dt1 = dtypes[ i ]; 52 o = PROMOTION_RULES[ dt1 ]; 53 tmp = {}; 54 for ( j = 0; j < ntypes; j++ ) { 55 dt2 = dtypes[ j ]; 56 tmp[ dt2 ] = o[ dt2 ]; 57 } 58 out[ dt1 ] = tmp; 59 } 60 return out; 61 } 62 63 64 // MAIN // 65 66 /** 67 * Returns the ndarray data type with the smallest size and closest "kind" to which ndarray data types can be safely cast. 68 * 69 * @param {string} [dtype1] - ndarray data type 70 * @param {string} [dtype2] - ndarray data type 71 * @returns {(Object|integer|string|null)} promotion rule(s) or null 72 * 73 * @example 74 * var table = promotionRules(); 75 * // returns {...} 76 * 77 * @example 78 * var dt = promotionRules( 'float32', 'uint32' ); 79 * // returns 'float64' 80 * 81 * @example 82 * var dt = promotionRules( 'binary', 'generic' ); 83 * // returns -1 84 * 85 * @example 86 * var dt = promotionRules( 'float32', 'foo' ); 87 * // returns null 88 */ 89 function promotionRules( dtype1, dtype2 ) { 90 var o; 91 if ( arguments.length === 0 ) { 92 return generateFullTable(); 93 } 94 if ( hasOwnProp( PROMOTION_RULES, dtype1 ) ) { 95 o = PROMOTION_RULES[ dtype1 ]; 96 if ( hasOwnProp( o, dtype2 ) ) { 97 return o[ dtype2 ]; 98 } 99 } 100 return null; 101 } 102 103 104 // EXPORTS // 105 106 module.exports = promotionRules;