expand_strides.js (1922B)
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 abs = require( '@stdlib/math/base/special/abs' ); 24 25 26 // MAIN // 27 28 /** 29 * Expands a strides array to accommodate an expanded array shape (i.e., an array shape with prepended singleton dimensions). 30 * 31 * @private 32 * @param {NonNegativeInteger} ndims - number of dimensions 33 * @param {Array} shape - expanded array shape 34 * @param {Array} strides - strides array 35 * @param {string} order - memory layout order 36 * @returns {Array} output strides array 37 * 38 * @example 39 * var out = expandStrides( 4, [ 1, 1, 2, 2 ], [ 1, 2 ], 'column-major' ); 40 * // returns [ 1, 1, 1, 2 ] 41 * 42 * @example 43 * var out = expandStrides( 4, [ 1, 1, 2, 2 ], [ 2, 1 ], 'row-major' ); 44 * // returns [ 4, 4, 2, 1 ] 45 */ 46 function expandStrides( ndims, shape, strides, order ) { 47 var out; 48 var N; 49 var s; 50 var i; 51 var j; 52 53 N = strides.length; 54 j = ndims - N; 55 out = []; 56 if ( order === 'row-major' ) { 57 s = abs( strides[ 0 ] ) * shape[ j ]; // at `j` is the size of the first non-prepended dimension 58 for ( i = 0; i < j; i++ ) { 59 out.push( s ); 60 } 61 for ( i = 0; i < N; i++ ) { 62 out.push( strides[ i ] ); 63 } 64 } else { // column-major 65 for ( i = 0; i < j; i++ ) { 66 out.push( 1 ); 67 } 68 for ( i = 0; i < N; i++ ) { 69 out.push( strides[ i ] ); 70 } 71 } 72 return out; 73 } 74 75 76 // EXPORTS // 77 78 module.exports = expandStrides;