gfill_by.js (1527B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 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 * Fills a strided array according to a provided callback function. 25 * 26 * @param {PositiveInteger} N - number of indexed elements 27 * @param {Collection} x - input array/collection 28 * @param {integer} stride - index increment 29 * @param {Callback} clbk - callback 30 * @param {*} [thisArg] - execution context 31 * @returns {Collection} input array/collection 32 * 33 * @example 34 * var x = [ -2.0, 1.0, 3.0, -5.0, 4.0, 0.0, -1.0, -3.0 ]; 35 * 36 * function fill() { 37 * return 5.0; 38 * } 39 * 40 * gfillBy( x.length, x, 1, fill ); 41 * // x => [ 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0 ] 42 */ 43 function gfillBy( N, x, stride, clbk, thisArg ) { 44 var ix; 45 var i; 46 47 if ( N <= 0 ) { 48 return x; 49 } 50 if ( stride < 0 ) { 51 ix = (1-N) * stride; 52 } else { 53 ix = 0; 54 } 55 for ( i = 0; i < N; i++ ) { 56 x[ ix ] = clbk.call( thisArg, x[ ix ], i, ix, x ); 57 ix += stride; 58 } 59 return x; 60 } 61 62 63 // EXPORTS // 64 65 module.exports = gfillBy;