time-to-botec

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

tojson.js (1935B)


      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 real = require( '@stdlib/complex/real' );
     24 var imag = require( '@stdlib/complex/imag' );
     25 
     26 
     27 // MAIN //
     28 
     29 /**
     30 * Serializes an ndarray as a JSON object.
     31 *
     32 * ## Notes
     33 *
     34 * -   The method does **not** serialize data outside of the buffer region defined by the array configuration.
     35 *
     36 * @private
     37 * @returns {Object} JSON representation
     38 */
     39 function toJSON() {
     40 	/* eslint-disable no-invalid-this */
     41 	var out;
     42 	var len;
     43 	var v;
     44 	var i;
     45 
     46 	len = this._length;
     47 
     48 	// Build an object containing all ndarray properties needed to revive a serialized ndarray...
     49 	out = {};
     50 	out.type = 'ndarray';
     51 	out.dtype = this.dtype;
     52 	out.flags = {}; // TODO: reserved for future use
     53 	out.order = this._order;
     54 	out.shape = this._shape.slice();
     55 	out.strides = this._strides.slice();
     56 
     57 	// Flip the signs of negative strides:
     58 	for ( i = 0; i < len; i++ ) {
     59 		if ( out.strides[ i ] < 0 ) {
     60 			out.strides[ i ] *= -1;
     61 		}
     62 	}
     63 	// Cast data to generic array...
     64 	out.data = [];
     65 	if ( out.dtype === 'complex64' || out.dtype === 'complex128' ) {
     66 		for ( i = 0; i < len; i++ ) {
     67 			v = this.iget( i );
     68 			out.data.push( real( v ), imag( v ) );
     69 		}
     70 	} else {
     71 		for ( i = 0; i < len; i++ ) {
     72 			out.data.push( this.iget( i ) );
     73 		}
     74 	}
     75 	return out;
     76 
     77 	/* eslint-enable no-invalid-this */
     78 }
     79 
     80 
     81 // EXPORTS //
     82 
     83 module.exports = toJSON;