Skip to content

writetome51/error-if-index-not-valid-after-offset-was-added

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

errorIfIndexNotValidAfterOffsetWasAdded(
      index,
      arrayLength
): void

Triggers error if index is not valid, assuming an offset was recently added to it.
For example, if you're writing a getIndex() function that gives you the option of adding
an offset to modify the index it returns, errorIfIndexNotValidAfterOffsetWasAdded()
might come in handy. For more info, read the example below.

Example

function getIndexSlightlyOff(value, array, offset){
    let index = array.indexOf(value);
    index += offset;
    // Now check if index still valid:
    errorIfIndexNotValidAfterOffsetWasAdded(index, array.length);
    return index;
}

let arr = [1,2,3,4,5];
let index = getIndexSlightlyOff(5, arr, 1);
// Error: "After the offset was added to the index, the resulting 
// index was too high for this array"

let arr = [1,2,3,4,5];
let index = getIndexSlightlyOff(2, arr, -2);
// Error: "After the offset was added to the index, the resulting 
// index was a negative number. This is not allowed."

Installation

npm install error-if-index-not-valid-after-offset-was-added

Loading

// if using TypeScript:
import { errorIfIndexNotValidAfterOffsetWasAdded } 
    from 'error-if-index-not-valid-after-offset-was-added';
// if using ES5 JavaScript:
var errorIfIndexNotValidAfterOffsetWasAdded = 
    require('error-if-index-not-valid-after-offset-was-added')
    .errorIfIndexNotValidAfterOffsetWasAdded;

License

MIT

About

Function triggers error if passed index is not valid, assuming an offset was recently added to it

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published