Skip to content

Commit

Permalink
chore: early exit when encoding invalid numbers
Browse files Browse the repository at this point in the history
Before this change, we checked the validity of every number during
encoding. Now, we stop if we find an invalid one.

In my testing, this was about twice as fast for invalid inputs. It had
no performance impact for valid inputs, but should theoretically avoid
an unnecessary array allocation.
  • Loading branch information
EvanHahn committed Nov 26, 2023
1 parent ebca95e commit 77e9fe3
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 7 deletions.
4 changes: 2 additions & 2 deletions cjs/sqids.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/sqids.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions esm/sqids.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions src/sqids.ts
Original file line number Diff line number Diff line change
Expand Up @@ -628,8 +628,10 @@ export default class Sqids {
return ''
}

const inRangeNumbers = numbers.filter((n) => n >= 0 && n <= this.maxValue())
if (inRangeNumbers.length !== numbers.length) {
const areAllNumbersInRange = numbers.every(
(n) => n >= 0 && n <= this.maxValue(),
)
if (!areAllNumbersInRange) {
throw new Error(
`Encoding supports numbers between 0 and ${this.maxValue()}`,
)
Expand Down

0 comments on commit 77e9fe3

Please sign in to comment.