safe-integer-ts
Version:
Newtype wrapper of number type as safe-integer (53-bit precise integer)
61 lines • 2.14 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.toSafeInteger = exports.parseSafeInteger = exports.asSafeInteger = exports.isSafeInteger = void 0;
/**
* Checks if an unknown value is safe integer without any conversion.
*/
exports.isSafeInteger = Number.isSafeInteger;
/**
* Casts an unknown value as safe integer without any conversion; or null if unable.
*/
exports.asSafeInteger = (value) => Number.isSafeInteger(value)
? value
: null;
/**
* Parses a string as safe integer; or null if unable.
*
* This function just forwards to [Number.parseInt()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseInt).
*/
exports.parseSafeInteger = (str, radix) => exports.asSafeInteger(Number.parseInt(str, radix));
/**
* Tries to convert an unknown value to safe integer, using some conversions if necessary: `Math.round`, `parseInt` or `.valueOf`.
*
* Mapping:
*
* - number:
* - safe integer: the value
* - finite number: `Math.round` and `asSafeInteger` is used.
* - infinity, NaN: null
* - string: `parseInt` and `asSafeInteger` is used.
* - object:
* - non-null and has `valueOf`: `.valueOf()` and `asSafeInteger` is used.
* - other: null
* - undefined, boolean, function and anything else: null
*/
// TODO: Support bigint in future
exports.toSafeInteger = (value) => {
switch (typeof value) {
case "number":
return numberToSafeInteger(value);
case "string":
return exports.parseSafeInteger(value);
case "object":
return objectToSafeInteger(value);
default:
return null;
}
};
const numberToSafeInteger = (value) => Number.isFinite(value)
? exports.asSafeInteger(Math.round(value))
: null;
const objectToSafeInteger = (obj) => {
var _a;
if (typeof ((_a = obj) === null || _a === void 0 ? void 0 : _a.valueOf) !== "function") {
return null;
}
const value = obj.valueOf();
return typeof value === "number"
? numberToSafeInteger(value)
: null;
};
//# sourceMappingURL=index.js.map