validate.js (2215B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2021 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 isPlainObject = require( '@stdlib/assert/is-plain-object' ); 24 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 25 var contains = require( '@stdlib/assert/contains' ); 26 var orders = require( '@stdlib/ndarray/orders' ); 27 var dtypes = require( '@stdlib/ndarray/dtypes' ); 28 29 30 // VARIABLES // 31 32 var ORDERS = orders(); 33 var DTYPES = dtypes(); 34 35 36 // MAIN // 37 38 /** 39 * Validates function options. 40 * 41 * @private 42 * @param {Object} opts - destination object 43 * @param {Object} options - options 44 * @param {string} [options.dtype] - output array data type 45 * @param {string} [options.order] - output array order 46 * @returns {(Error|null)} null or an error object 47 * 48 * @example 49 * var opts = {}; 50 * var options = { 51 * 'order': 'row-major' 52 * }; 53 * var err = validate( opts, options ); 54 * if ( err ) { 55 * throw err; 56 * } 57 */ 58 function validate( opts, options ) { 59 if ( !isPlainObject( options ) ) { 60 return new TypeError( 'invalid argument. Options argument must be a plain object. Value: `' + options + '`.' ); 61 } 62 if ( hasOwnProp( options, 'dtype' ) ) { 63 opts.dtype = options.dtype; 64 if ( !contains( DTYPES, opts.dtype ) ) { 65 return new TypeError( 'invalid option. `dtype` option must be a recognized/supported data type. Option: `' + opts.dtype + '`.' ); 66 } 67 } 68 if ( hasOwnProp( options, 'order' ) ) { 69 opts.order = options.order; 70 if ( !contains( ORDERS, opts.order ) ) { 71 return new TypeError( 'invalid option. `order` option must be a recognized/supported data type. Option: `' + opts.order + '`.' ); 72 } 73 } 74 return null; 75 } 76 77 78 // EXPORTS // 79 80 module.exports = validate;