main.js (2128B)
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 isCollection = require( '@stdlib/assert/is-collection' ); 24 var getType = require( './../../dtype' ); 25 var ctors = require( './../../ctors' ); 26 27 28 // MAIN // 29 30 /** 31 * Converts an array to the same data type as a second input array. 32 * 33 * @param {Collection} x - array to convert 34 * @param {(Array|TypedArray)} y - array having the desired output data type 35 * @throws {TypeError} first argument must be an array-like object 36 * @throws {TypeError} second argument must have a recognized data type 37 * @returns {(Array|TypedArray)} output array 38 * 39 * @example 40 * var Float64Array = require( '@stdlib/array/float64' ); 41 * 42 * var y = new Float64Array( 0 ); 43 * 44 * var x = [ 1.0, 2.0, 3.0, 4.0 ]; 45 * var out = convertSame( x, y ); 46 * // returns <Float64Array>[ 1.0, 2.0, 3.0, 4.0 ] 47 */ 48 function convertSame( x, y ) { 49 var dtype; 50 var ctor; 51 var out; 52 var len; 53 var i; 54 if ( !isCollection( x ) ) { 55 throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + x + '`.' ); 56 } 57 dtype = getType( y ); 58 ctor = ctors( dtype ); 59 if ( ctor === null ) { 60 throw new TypeError( 'invalid argument. Second argument must have a recognized data type. Value: `' + dtype + '`.' ); 61 } 62 len = x.length; 63 if ( dtype === 'generic' ) { 64 out = []; 65 for ( i = 0; i < len; i++ ) { 66 out.push( x[ i ] ); // ensure "fast" elements 67 } 68 return out; 69 } 70 out = new ctor( len ); 71 for ( i = 0; i < len; i++ ) { 72 out[ i ] = x[ i ]; 73 } 74 return out; 75 } 76 77 78 // EXPORTS // 79 80 module.exports = convertSame;