main.js (1920B)
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 clampIndex = require( './../../../base/clamp-index' ); 24 var wrapIndex = require( './../../../base/wrap-index' ); 25 26 27 // MAIN // 28 29 /** 30 * Returns an index given an index mode. 31 * 32 * @param {integer} idx - index 33 * @param {NonNegativeInteger} max - maximum index 34 * @param {string} mode - specifies how to handle an index outside the interval `[0,max]` 35 * @throws {RangeError} index out-of-bounds 36 * @returns {integer} index 37 * 38 * @example 39 * var idx = ind( 2, 9, 'clamp' ); 40 * // returns 2 41 * 42 * idx = ind( 10, 9, 'clamp' ); 43 * // returns 9 44 * 45 * idx = ind( -1, 9, 'clamp' ); 46 * // returns 0 47 * 48 * @example 49 * var idx = ind( 2, 9, 'wrap' ); 50 * // returns 2 51 * 52 * idx = ind( 10, 9, 'wrap' ); 53 * // returns 0 54 * 55 * idx = ind( -1, 9, 'wrap' ); 56 * // returns 9 57 * 58 * @example 59 * var idx = ind( 2, 9, 'throw' ); 60 * // returns 2 61 * 62 * idx = ind( 10, 9, 'throw' ); 63 * // throws <RangeError> 64 * 65 * idx = ind( -1, 9, 'throw' ); 66 * // throws <RangeError> 67 */ 68 function ind( idx, max, mode ) { 69 if ( mode === 'clamp' ) { 70 return clampIndex( idx, max ); 71 } 72 if ( mode === 'wrap' ) { 73 return wrapIndex( idx, max ); 74 } 75 if ( idx < 0 || idx > max ) { 76 throw new RangeError( 'invalid argument. Index must be on the interval: [0,' + max + ']. Value: `' + idx + '`.' ); 77 } 78 return idx; 79 } 80 81 82 // EXPORTS // 83 84 module.exports = ind;