validate.js (2644B)
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 contains = require( '@stdlib/assert/contains' ); 24 var isArray = require( '@stdlib/assert/is-array' ); 25 var isObject = require( '@stdlib/assert/is-object' ); 26 var isString = require( '@stdlib/assert/is-string' ).isPrimitive; 27 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 28 29 30 // VARIABLES // 31 32 var METHODS = [ 'min', 'max', 'average', 'dense', 'ordinal' ]; 33 var MISSING = [ 'last', 'first', 'remove' ]; 34 35 36 // MAIN // 37 38 /** 39 * Validates function options. 40 * 41 * @private 42 * @param {Object} opts - destination for validated options 43 * @param {Object} options - function options 44 * @param {string} [options.method] - method determining how ties are treated 45 * @param {string} [opts.missing] - determines where missing values go (`first`,`last`, or `remove`) 46 * @param {Array} [opts.encoding] - array of values encoding missing values 47 * @returns {(null|Error)} null or an error 48 */ 49 function validate( opts, options ) { 50 if ( !isObject( options ) ) { 51 return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); 52 } 53 if ( hasOwnProp( options, 'encoding' ) ) { 54 opts.encoding = options.encoding; 55 if ( !isArray( opts.encoding ) ) { 56 return new TypeError( 'invalid option. `encoding` option must be an array. Option: `' + opts.encoding + '`.' ); 57 } 58 } 59 if ( hasOwnProp( options, 'method' ) ) { 60 opts.method = options.method; 61 if ( !isString( opts.method ) || !contains( METHODS, opts.method ) ) { 62 return new TypeError( 'invalid option. `method` must be one of the following values: `average`, `min`, `max`, `dense`, or `ordinal`. Option: `' + opts.method + '`.' ); 63 } 64 } 65 if ( hasOwnProp( options, 'missing' ) ) { 66 opts.missing = options.missing; 67 if ( !isString( opts.missing ) || !contains( MISSING, opts.missing ) ) { 68 return new TypeError( 'invalid option. `missing` must be one of the following values: `last`, `first`, or `remove`. Option: `' + opts.missing + '`.' ); 69 } 70 } 71 return null; 72 } 73 74 75 // EXPORTS // 76 77 module.exports = validate;