validate.js (2176B)
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 isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; 26 var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; 27 28 29 // MAIN // 30 31 /** 32 * Validates function options. 33 * 34 * @private 35 * @param {Object} opts - destination for function options 36 * @param {Options} options - function options 37 * @param {NonNegativeInteger} [options.depth] - depth to flatten 38 * @param {boolean} [options.copy] - boolean indicating whether to deep copy array elements 39 * @returns {(Error|null)} error or null 40 * 41 * @example 42 * var opts = {}; 43 * var options = { 44 * 'depth': 10, 45 * 'copy': false 46 * }; 47 * var err = validate( opts, options ); 48 * if ( err ) { 49 * throw err; 50 * } 51 */ 52 function validate( opts, options ) { 53 if ( !isObject( options ) ) { 54 return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); 55 } 56 if ( hasOwnProp( options, 'depth' ) ) { 57 opts.depth = options.depth; 58 if ( !isNonNegativeInteger( opts.depth ) ) { 59 return new TypeError( 'invalid option. `depth` option must be a nonnegative integer. Option: `' + opts.depth + '`.' ); 60 } 61 } 62 if ( hasOwnProp( options, 'copy' ) ) { 63 opts.copy = options.copy; 64 if ( !isBoolean( opts.copy ) ) { 65 return new TypeError( 'invalid option. `copy` option must be a boolean primitive. Option: `' + opts.copy + '`.' ); 66 } 67 } 68 return null; 69 } 70 71 72 // EXPORTS // 73 74 module.exports = validate;