to_json.js (1746B)
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 isTypedArray = require( '@stdlib/assert/is-typed-array' ); 24 var typeName = require( './type.js' ); 25 26 27 // MAIN // 28 29 /** 30 * Returns a JSON representation of a typed array. 31 * 32 * ## Notes 33 * 34 * - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1]. 35 * 36 * [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson 37 * 38 * @param {TypedArray} arr - typed array to serialize 39 * @throws {TypeError} first argument must be a typed array 40 * @returns {Object} JSON representation 41 * 42 * @example 43 * var Float64Array = require( '@stdlib/array/float64' ); 44 * 45 * var arr = new Float64Array( [ 5.0, 3.0 ] ); 46 * var json = toJSON( arr ); 47 * // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } 48 */ 49 function toJSON( arr ) { 50 var out; 51 var i; 52 if ( !isTypedArray( arr ) ) { 53 throw new TypeError( 'invalid argument. Must provide a typed array. Value: `' + arr + '`.' ); 54 } 55 out = {}; 56 out.type = typeName( arr ); 57 out.data = []; 58 for ( i = 0; i < arr.length; i++ ) { 59 out.data.push( arr[ i ] ); 60 } 61 return out; 62 } 63 64 65 // EXPORTS // 66 67 module.exports = toJSON;