|
1 |
| -# errorIfIndexIsNegative(index): void |
| 1 | +# errorIfIndexNotValidAfterOffsetWasAdded(<br> index,<br> arrayLength<br>): void |
2 | 2 |
|
3 |
| -Triggers error if `index` is negative number, saying "value not found in array". |
4 |
| -This function is intended to be called after you've called Array.indexOf(), or any |
5 |
| -function that returns a negative number if the value being searched for in the array |
6 |
| -was not found. You then pass that resulting index to this function to make sure if |
7 |
| -the value was found. |
| 3 | +Triggers error if `index` is not valid, assuming an offset was recently added to it. |
| 4 | +For example, if you're writing a getIndex() function that gives you the option of adding |
| 5 | +an offset to modify the index it returns, `errorIfIndexNotValidAfterOffsetWasAdded()` |
| 6 | +might come in handy. For more info, read the example below. |
8 | 7 |
|
9 | 8 | ## Example
|
10 |
| -``` |
11 |
| -let arr = [1,2,3,4]; |
12 |
| -let index = arr.indexOf(5); |
13 |
| -errorIfIndexIsNegative(index); |
14 |
| -// "Error: value not found in array" |
| 9 | +```ts |
| 10 | +function getIndexSlightlyOff(value, array, offset){ |
| 11 | + let index = array.indexOf(value); |
| 12 | + index += offset; |
| 13 | + // Now check if index still valid: |
| 14 | + errorIfIndexNotValidAfterOffsetWasAdded(index, array.length); |
| 15 | + return index; |
| 16 | +} |
| 17 | + |
| 18 | +let arr = [1,2,3,4,5]; |
| 19 | +let index = getIndexSlightlyOff(5, arr, 1); |
| 20 | +// Error: "After the offset was added to the index, the resulting |
| 21 | +// index was too high for this array" |
| 22 | + |
| 23 | +let arr = [1,2,3,4,5]; |
| 24 | +let index = getIndexSlightlyOff(2, arr, -2); |
| 25 | +// Error: "After the offset was added to the index, the resulting |
| 26 | +// index was a negative number. This is not allowed." |
15 | 27 | ```
|
16 | 28 |
|
17 | 29 | ## Installation
|
18 |
| -`npm install error-if-index-is-negative` |
| 30 | +`npm install error-if-index-not-valid-after-offset-was-added` |
19 | 31 |
|
20 | 32 | ## Loading
|
21 |
| -``` |
| 33 | +```ts |
22 | 34 | // if using TypeScript:
|
23 |
| -import { errorIfIndexIsNegative } from 'error-if-index-is-negative'; |
| 35 | +import { errorIfIndexNotValidAfterOffsetWasAdded } |
| 36 | + from 'error-if-index-not-valid-after-offset-was-added'; |
24 | 37 | // if using ES5 JavaScript:
|
25 |
| -var errorIfIndexIsNegative = |
26 |
| - require('error-if-index-is-negative').errorIfIndexIsNegative; |
| 38 | +var errorIfIndexNotValidAfterOffsetWasAdded = |
| 39 | + require('error-if-index-not-valid-after-offset-was-added') |
| 40 | + .errorIfIndexNotValidAfterOffsetWasAdded; |
27 | 41 | ```
|
28 | 42 |
|
29 | 43 | ## License
|
|
0 commit comments