flatten_array.js (2070B)
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 copy = require( './../../copy' ); 24 var isArray = require( '@stdlib/assert/is-array' ); 25 var defaults = require( './defaults.js' ); 26 var validate = require( './validate.js' ); 27 var recurse = require( './recurse.js' ); 28 29 30 // MAIN // 31 32 /** 33 * Flattens an array. 34 * 35 * @param {Array} arr - input array 36 * @param {Options} [options] - function options 37 * @param {NonNegativeInteger} [options.depth] - maximum depth to flatten 38 * @param {boolean} [options.copy=false] - boolean indicating whether to deep copy array elements 39 * @throws {TypeError} first argument must be an array 40 * @throws {TypeError} options argument must be an object 41 * @throws {TypeError} must provide valid options 42 * @returns {Array} flattened array 43 * 44 * @example 45 * var arr = [ 1, [2, [3, [4, [ 5 ], 6], 7], 8], 9 ]; 46 * 47 * var out = flattenArray( arr ); 48 * // returns [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 49 */ 50 function flattenArray( arr, options ) { 51 var opts; 52 var err; 53 var out; 54 if ( !isArray( arr ) ) { 55 throw new TypeError( 'invalid argument. First argument must be an array. Value: `' + arr + '`.' ); 56 } 57 opts = { 58 'copy': defaults.copy, 59 'depth': defaults.depth 60 }; 61 if ( arguments.length > 1 ) { 62 err = validate( opts, options ); 63 if ( err ) { 64 throw err; 65 } 66 } 67 if ( opts.depth === 0 ) { 68 out = arr; 69 } else { 70 out = recurse( [], arr, opts.depth ); 71 } 72 if ( opts.copy ) { 73 return copy( out ); 74 } 75 return out; 76 } 77 78 79 // EXPORTS // 80 81 module.exports = flattenArray;