main.js (2540B)
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 SAFE_CASTS = require( './safe_casts.json' ); 26 27 28 // VARIABLES // 29 30 var TABLE; 31 32 33 // FUNCTIONS // 34 35 /** 36 * Generates a full table of safe casts for each array data type. 37 * 38 * @private 39 * @returns {Object} table 40 */ 41 function generateFullTable() { 42 var dtypes; 43 var ntypes; 44 var out; 45 var tmp; 46 var dt1; 47 var dt2; 48 var o; 49 var j; 50 var i; 51 52 out = {}; 53 dtypes = objectKeys( SAFE_CASTS ); 54 ntypes = dtypes.length; 55 for ( i = 0; i < ntypes; i++ ) { 56 dt1 = dtypes[ i ]; 57 o = SAFE_CASTS[ dt1 ]; 58 tmp = {}; 59 for ( j = 0; j < ntypes; j++ ) { 60 dt2 = dtypes[ j ]; 61 tmp[ dt2 ] = o[ dt2 ]; 62 } 63 out[ dt1 ] = tmp; 64 } 65 return out; 66 } 67 68 /** 69 * Generates a table of safe casts for each array data type. 70 * 71 * @private 72 * @returns {Object} table 73 */ 74 function generateTable() { 75 var dtypes; 76 var ntypes; 77 var out; 78 var tmp; 79 var dt1; 80 var dt2; 81 var o; 82 var j; 83 var i; 84 85 out = {}; 86 dtypes = objectKeys( SAFE_CASTS ); 87 ntypes = dtypes.length; 88 for ( i = 0; i < ntypes; i++ ) { 89 dt1 = dtypes[ i ]; 90 o = SAFE_CASTS[ dt1 ]; 91 tmp = []; 92 for ( j = 0; j < ntypes; j++ ) { 93 dt2 = dtypes[ j ]; 94 if ( o[ dt2 ] === 1 ) { 95 tmp.push( dt2 ); 96 } 97 } 98 out[ dt1 ] = tmp; 99 } 100 return out; 101 } 102 103 104 // MAIN // 105 106 /** 107 * Returns a list of array data types to which a provided array data type can be safely cast. 108 * 109 * @param {string} [dtype] - array data type 110 * @returns {(Object|StringArray|null)} list of array data types or null 111 * 112 * @example 113 * var list = safeCasts( 'float32' ); 114 * // returns [...] 115 */ 116 function safeCasts( dtype ) { 117 if ( arguments.length === 0 ) { 118 return generateFullTable(); 119 } 120 if ( TABLE === void 0 ) { 121 // Lazily generate table... 122 TABLE = generateTable(); 123 } 124 if ( hasOwnProp( TABLE, dtype ) ) { 125 return TABLE[ dtype ].slice(); 126 } 127 return null; 128 } 129 130 131 // EXPORTS // 132 133 module.exports = safeCasts;