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