validate.js (2537B)
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 isObject = require( '@stdlib/assert/is-plain-object' ); 24 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 25 var isArray = require( '@stdlib/assert/is-array' ); 26 var isOrder = require( './../../base/assert/is-order' ); 27 var isIndexMode = require( './../../base/assert/is-index-mode' ); 28 29 30 // MAIN // 31 32 /** 33 * Validates function options. 34 * 35 * @private 36 * @param {Object} opts - destination object 37 * @param {Options} options - function options 38 * @param {(StringArray|string)} [options.mode] - specifies how to handle subscripts which exceed array dimensions 39 * @param {string} [options.order] - specifies whether an array is row-major (C-style) or column-major (Fortran-style) 40 * @returns {(Error|null)} null or an error object 41 * 42 * @example 43 * var opts = {}; 44 * var options = { 45 * 'mode': 'throw', 46 * 'order': 'column-major' 47 * }; 48 * var err = validate( opts, options ); 49 * if ( err ) { 50 * throw err; 51 * } 52 */ 53 function validate( opts, options ) { 54 var i; 55 if ( !isObject( options ) ) { 56 return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' ); 57 } 58 if ( hasOwnProp( options, 'mode' ) ) { 59 opts.mode = options.mode; 60 if ( !isArray( opts.mode ) ) { 61 opts.mode = [ opts.mode ]; 62 } else if ( opts.mode.length === 0 ) { 63 return new TypeError( 'invalid option. `mode` option cannot be an empty array.' ); 64 } 65 for ( i = 0; i < opts.mode.length; i++ ) { 66 if ( !isIndexMode( opts.mode[ i ] ) ) { 67 return new TypeError( 'invalid option. `mode` option must be a supported/recognized mode. Option: `' + opts.mode[ i ] + '`.' ); 68 } 69 } 70 } 71 if ( hasOwnProp( options, 'order' ) ) { 72 opts.order = options.order; 73 if ( !isOrder( opts.order ) ) { 74 return new TypeError( 'invalid option. `order` option must be a supported/recognized order. Option: `' + opts.order + '`.' ); 75 } 76 } 77 return null; 78 } 79 80 81 // EXPORTS // 82 83 module.exports = validate;