time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

main.js (1927B)


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