MCPcopy
hub / github.com/huggingface/transformers.js / safeIndex

Function safeIndex

packages/transformers/src/utils/tensor.js:1285–1301  ·  view source on GitHub ↗

* Safely calculate the index for an array of a given size, allowing negative indexing. * @param {number} index The index that will be used. * @param {number} size The size of the array. * @param {number|null} [dimension=null] The dimension that the index is for (optional). * @returns {number} Th

(index, size, dimension = null, boundsCheck = true)

Source from the content-addressed store, hash-verified

1283 * @private
1284 */
1285function safeIndex(index, size, dimension = null, boundsCheck = true) {
1286 if (index < -size || index >= size) {
1287 if (boundsCheck) {
1288 throw new Error(
1289 `IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`,
1290 );
1291 } else {
1292 return index < -size ? 0 : size;
1293 }
1294 }
1295
1296 if (index < 0) {
1297 // Negative indexing, ensuring positive index
1298 index = ((index % size) + size) % size;
1299 }
1300 return index;
1301}
1302
1303/**
1304 * Concatenates an array of tensors along a specified dimension.

Callers 8

_getitemMethod · 0.85
sliceMethod · 0.85
normalize_Method · 0.85
calc_unsqueeze_dimsFunction · 0.85
catFunction · 0.85
reduce_helperFunction · 0.85
std_meanFunction · 0.85
meanFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected