clampIndex

Restrict an index to the interval [0,max].

Usage

var clampIndex = require( '@stdlib/ndarray/base/clamp-index' );

clampIndex( idx, max )

Restricts an index to the interval [0,max].

var idx = clampIndex( 2, 10 );
// returns 2

idx = clampIndex( -5, 10 );
// returns 0

idx = clampIndex( 15, 10 );
// returns 10

Examples

var discreteUniform = require( '@stdlib/random/base/discrete-uniform' );
var clampIndex = require( '@stdlib/ndarray/base/clamp-index' );

var idx;
var out;
var i;

for ( i = 0; i < 100; i++ ) {
    idx = discreteUniform( -20, 20 );
    out = clampIndex( idx, 10 );
    console.log( '%d => [%d,%d] => %d', idx, 0, 10, out );
}
Did you find this page helpful?