copy.js (1936B)
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 isArray = require( '@stdlib/assert/is-array' ); 24 var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; 25 var PINF = require( '@stdlib/constants/float64/pinf' ); 26 var deepCopy = require( './deep_copy.js' ); 27 28 29 // MAIN // 30 31 /** 32 * Copies or deep clones a value to an arbitrary depth. 33 * 34 * @param {*} value - value to copy 35 * @param {NonNegativeInteger} [level=+infinity] - copy depth 36 * @throws {TypeError} `level` must be a nonnegative integer 37 * @returns {*} value copy 38 * 39 * @example 40 * var out = copy( 'beep' ); 41 * // returns 'beep' 42 * 43 * @example 44 * var value = [ 45 * { 46 * 'a': 1, 47 * 'b': true, 48 * 'c': [ 1, 2, 3 ] 49 * } 50 * ]; 51 * var out = copy( value ); 52 * // returns [ { 'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ] 53 * 54 * var bool = ( value[0].c === out[0].c ); 55 * // returns false 56 */ 57 function copy( value, level ) { 58 var out; 59 if ( arguments.length > 1 ) { 60 if ( !isNonNegativeInteger( level ) ) { 61 throw new TypeError( 'invalid argument. `level` must be a nonnegative integer. Value: `' + level + '`.' ); 62 } 63 if ( level === 0 ) { 64 return value; 65 } 66 } else { 67 level = PINF; 68 } 69 out = ( isArray( value ) ) ? new Array( value.length ) : {}; 70 return deepCopy( value, out, [value], [out], level ); 71 } 72 73 74 // EXPORTS // 75 76 module.exports = copy;