Open In App

How to Check a Value is Safe Integer using Lodash?

Last Updated : 30 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Safe Integer is the range of integers that JavaScript can precisely represent without losing precision. In Lodash, you can check if a value is a safe integer using mrthods like _.isSafeInteger() or combinations like _.overEvery(), _.isInteger(), and _.inRange(). Safe Integers are integers between the range -(253 â€“ 1) to (253 â€“ 1).

Use the below npm command to install Lodash library. To install the npm, you need to install Node.js an then you can use npm command to run and install Lodash.

npm i lodash

Approach 1: Using _.isSafeInteger() Method

In this approach, we are using _.isSafeInteger() method from Lodash to directly check if a value is within the safe integer range, returning true if it is safe, and false otherwise. This method is simple for validating safe integers in JavaScript.

Syntax:

_.isSafeInteger( value )

Example: The below example uses _.isSafeInteger() method to check if a value is a safe integer using Lodash.

JavaScript
const _ = require('lodash');

const value1 = 42;
const value2 = 0.123;

console.log(_.isSafeInteger(value1));
console.log(_.isSafeInteger(value2)); 

Output:

true
false

Approach 2: Using _.overEvery(), _.inRange(), _.partial() and _.isInteger() Methods

In this approach, we are using _.overEvery() along with _.isInteger(), _.partial(), and _.inRange() from Lodash to create a function that checks if a value is an integer and within the safe integer range, returning true if both conditions are met and false otherwise.

Syntax:

const isSafeInteger = _.overEvery(
_.isInteger,
_.partial(_.inRange, _, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
);

Example: The below example uses _.overEvery(), _.inRange(), _.partial(), and _.isInteger() methods to check if a value is a safe integer using Lodash.

JavaScript
const _ = require('lodash');

const value1 = 42;
const value2 = 0.123;

console.log(_.overEvery(
    _.isInteger, 
    _.partial(
        _.inRange, _, 
        Number.MIN_SAFE_INTEGER, 
        Number.MAX_SAFE_INTEGER)
    )(value1)
); 

console.log(_.overEvery(
    _.isInteger, 
    _.partial(
        _.inRange, _, 
        Number.MIN_SAFE_INTEGER, 
        Number.MAX_SAFE_INTEGER)
    )(value2)
); 

Output:

true
false

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads