ndarray.js (2541B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2021 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 ndarray = require( '@stdlib/ndarray/ctor' ); 24 var buffer = require( '@stdlib/ndarray/base/buffer' ); 25 var shape2strides = require( '@stdlib/ndarray/base/shape2strides' ); 26 var numel = require( '@stdlib/ndarray/base/numel' ); 27 28 29 // FUNCTIONS // 30 31 /** 32 * Copies an array-like object to a generic array. 33 * 34 * @private 35 * @param {ArrayLikeObject} x - input array 36 * @returns {Array} output array 37 */ 38 function copy( x ) { 39 var out; 40 var i; 41 42 out = []; 43 for ( i = 0; i < x.length; i++ ) { 44 out.push( x[ i ] ); 45 } 46 return out; 47 } 48 49 50 // MAIN // 51 52 /** 53 * Applies a function to an ndarray. 54 * 55 * @private 56 * @param {Function} fcn - function to apply 57 * @param {ndarray} x - input array 58 * @param {string} ydtype - output array data type 59 * @param {string} yorder - output array order 60 * @throws {TypeError} must provide an input array argument with a supported data type 61 * @returns {ndarray} output array 62 */ 63 function ndarrayfcn( fcn, x, ydtype, yorder ) { 64 var shape; 65 var buf; 66 var y; 67 68 // Check if we were provided a zero-dimensional array... 69 shape = copy( x.shape ); // Note: we need to copy the shape to avoid a shared shape object between `x` and `y` which could lead to unintended mutations (e.g., if either `x` or `y` is reshaped) 70 if ( shape.length === 0 ) { 71 buf = buffer( ydtype, 1 ); 72 y = ndarray( ydtype, buf, [], [ 0 ], 0, yorder ); 73 } else { 74 buf = buffer( ydtype, x.length || numel( shape ) ); // WARNING: `x.length` is a property found on ndarray instances, but not strictly necessary to describe an ndarray; accordingly, used here to avoid unnecessary computation, but a potential source of bugs if provided an ndarray-like object having a `length` property which is not equal to the product of the dimensions. 75 y = ndarray( ydtype, buf, shape, shape2strides( shape, yorder ), 0, yorder ); // eslint-disable-line max-len 76 } 77 fcn( x, y ); 78 return y; 79 } 80 81 82 // EXPORTS // 83 84 module.exports = ndarrayfcn;