Skip to content

Commit

Permalink
lib: support min/max values in validateInteger()
Browse files Browse the repository at this point in the history
This commit updates validateInteger() in two ways:

- Number.isInteger() is used instead of Number.isSafeInteger().
  This ensures that all integer values are supported.
- Minimum and maximum values are supported. They default to
  the min and max safe integer values, but can be customized.

PR-URL: #28810
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Richard Lau <riclau@uk.ibm.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
  • Loading branch information
cjihrig authored and targos committed Aug 2, 2019
1 parent e334c1f commit 386d5d7
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/internal/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const {
isArrayBufferView
} = require('internal/util/types');
const { signals } = internalBinding('constants').os;
const { MAX_SAFE_INTEGER, MIN_SAFE_INTEGER } = Number;

function isInt32(value) {
return value === (value | 0);
Expand Down Expand Up @@ -60,12 +61,16 @@ function parseMode(value, name, def) {
throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc);
}

const validateInteger = hideStackFrames((value, name) => {
if (typeof value !== 'number')
throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
if (!Number.isSafeInteger(value))
throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
});
const validateInteger = hideStackFrames(
(value, name, min = MIN_SAFE_INTEGER, max = MAX_SAFE_INTEGER) => {
if (typeof value !== 'number')
throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
if (!Number.isInteger(value))
throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
if (value < min || value > max)
throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
}
);

const validateInt32 = hideStackFrames(
(value, name, min = -2147483648, max = 2147483647) => {
Expand Down

0 comments on commit 386d5d7

Please sign in to comment.