assign.js (2291B)
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 // FUNCTIONS // 22 23 /** 24 * Generates a stride array from an array shape (row-major). 25 * 26 * @private 27 * @param {NonNegativeIntegerArray} shape - array shape 28 * @param {(Array|TypedArray|Object)} out - output object 29 * @returns {(Array|TypedArray|Object)} array strides 30 */ 31 function rowmajor( shape, out ) { 32 var ndims; 33 var s; 34 var i; 35 36 ndims = shape.length; 37 s = 1; 38 for ( i = ndims-1; i >= 0; i-- ) { 39 out[ i ] = s; 40 s *= shape[ i ]; 41 } 42 return out; 43 } 44 45 /** 46 * Generates a stride array from an array shape (column-major). 47 * 48 * @private 49 * @param {NonNegativeIntegerArray} shape - array shape 50 * @param {(Array|TypedArray|Object)} out - output object 51 * @returns {(Array|TypedArray|Object)} array strides 52 */ 53 function columnmajor( shape, out ) { 54 var s; 55 var i; 56 57 s = 1; 58 for ( i = 0; i < shape.length; i++ ) { 59 out[ i ] = s; 60 s *= shape[ i ]; 61 } 62 return out; 63 } 64 65 66 // MAIN // 67 68 /** 69 * Generates a stride array from an array shape. 70 * 71 * @param {NonNegativeIntegerArray} shape - array shape 72 * @param {string} order - specifies whether an array is row-major (C-style) or column-major (Fortran-style) 73 * @param {(Array|TypedArray|Object)} out - output object 74 * @returns {(Array|TypedArray|Object)} array strides 75 * 76 * @example 77 * var strides = [ 0, 0 ]; 78 * 79 * var out = shape2strides( [ 3, 2 ], 'row-major', strides ); 80 * // returns [ 2, 1 ] 81 * 82 * var bool = ( out === strides ); 83 * // returns true 84 * 85 * out = shape2strides( [ 3, 2 ], 'column-major', strides ); 86 * // returns [ 1, 3 ] 87 */ 88 function shape2strides( shape, order, out ) { 89 if ( order === 'column-major' ) { 90 return columnmajor( shape, out ); 91 } 92 return rowmajor( shape, out ); 93 } 94 95 96 // EXPORTS // 97 98 module.exports = shape2strides;