iset.js (2717B)
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 // MAIN // 22 23 /** 24 * Sets an array element located a specified linear view index. 25 * 26 * ## Notes 27 * 28 * - For zero-dimensional arrays, the first, and only, argument should be the value to set. 29 * 30 * @private 31 * @param {integer} [idx] - linear view index 32 * @param {*} v - value to set 33 * @returns {ndarray} ndarray instance 34 */ 35 function iset( idx, v ) { 36 /* eslint-disable no-invalid-this */ 37 var strides; 38 var shape; 39 var ndims; 40 var ind; 41 var s; 42 var i; 43 44 ndims = this._ndims; 45 if ( ndims === 0 ) { 46 if ( this._accessors ) { 47 this._buffer.set( idx, this._offset ); 48 } else { 49 this._buffer[ this._offset ] = idx; 50 } 51 return this; 52 } 53 if ( this._flags.ROW_MAJOR_CONTIGUOUS || this._flags.COLUMN_MAJOR_CONTIGUOUS ) { // eslint-disable-line max-len 54 // Trivial case where we have all positive strides... 55 if ( this._iterationOrder === 1 ) { 56 if ( this._accessors ) { 57 this._buffer.set( v, this._offset+idx ); 58 } else { 59 this._buffer[ this._offset+idx ] = v; 60 } 61 return this; 62 } 63 // Trivial case where we have all negative strides... 64 if ( this._iterationOrder === -1 ) { 65 if ( this._accessors ) { 66 this._buffer.set( v, this._offset-idx ); 67 } else { 68 this._buffer[ this._offset-idx ] = v; 69 } 70 return this; 71 } 72 } 73 // The approach which follows is to resolve a view index to its subscripts and then plug the subscripts into the standard formula for computing the linear index in the underlying data buffer... 74 shape = this._shape; 75 strides = this._strides; 76 ind = this._offset; 77 if ( this._order === 'column-major' ) { 78 for ( i = 0; i < ndims; i++ ) { 79 s = idx % shape[ i ]; 80 idx -= s; 81 idx /= shape[ i ]; 82 ind += s * strides[ i ]; 83 } 84 if ( this._accessors ) { 85 this._buffer.set( v, ind ); 86 } else { 87 this._buffer[ ind ] = v; 88 } 89 return this; 90 } 91 // Case: row-major 92 for ( i = ndims-1; i >= 0; i-- ) { 93 s = idx % shape[ i ]; 94 idx -= s; 95 idx /= shape[ i ]; 96 ind += s * strides[ i ]; 97 } 98 if ( this._accessors ) { 99 this._buffer.set( v, ind ); 100 } else { 101 this._buffer[ ind ] = v; 102 } 103 return this; 104 } 105 106 107 // EXPORTS // 108 109 module.exports = iset;