factory.js (2667B)
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 isPositiveIntegerArray = require( '@stdlib/assert/is-positive-integer-array' ).primitives; 24 var isObject = require( '@stdlib/assert/is-plain-object' ); 25 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 26 var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; 27 var defaults = require( './defaults.js' ); 28 var genFcn = require( './gen_fcn.js' ); 29 var wrapFlatten = require( './wrap_flatten.js' ); 30 var wrapFlattenCopy = require( './wrap_flatten_copy.js' ); 31 32 33 // MAIN // 34 35 /** 36 * Returns a function for flattening arrays having specified dimensions. 37 * 38 * @param {PositiveIntegerArray} dims - dimensions 39 * @param {Options} [options] - function options 40 * @param {boolean} [options.copy=false] - boolean indicating whether to deep copy array elements 41 * @throws {TypeError} first argument must be an array of positive integers 42 * @throws {TypeError} options argument must be an object 43 * @throws {TypeError} must provide valid options 44 * @returns {Function} flatten function 45 * 46 * @example 47 * var flatten = factory( [2,2], { 48 * 'copy': false 49 * }); 50 * 51 * var out = flatten( [[1,2],[3,4]] ); 52 * // returns [ 1, 2, 3, 4 ] 53 * 54 * out = flatten( [[5,6],[7,8]] ); 55 * // returns [ 5, 6, 7, 8 ] 56 */ 57 function factory( dims, options ) { 58 var copyFLG; 59 var flatten; 60 if ( !isPositiveIntegerArray( dims ) ) { 61 throw new TypeError( 'invalid argument. First argument must be an array of positive integers. Value: `' + dims + '`.' ); 62 } 63 copyFLG = defaults.copy; 64 if ( arguments.length > 1 ) { 65 if ( !isObject( options ) ) { 66 throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); 67 } 68 if ( hasOwnProp( options, 'copy' ) ) { 69 copyFLG = options.copy; 70 if ( !isBoolean( copyFLG ) ) { 71 throw new TypeError( 'invalid option. `copy` option must be a boolean primitive. Option: `' + copyFLG + '`.' ); 72 } 73 } 74 } 75 flatten = genFcn( dims ); 76 if ( copyFLG ) { 77 return wrapFlattenCopy( flatten ); 78 } 79 return wrapFlatten( flatten ); 80 } 81 82 83 // EXPORTS // 84 85 module.exports = factory;