Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for isSafeInteger #2529

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions test/objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,18 @@
assert.ok(_.isUndefined(void 0), 'undefined is undefined');
});

QUnit.test('isSafeInteger', function(assert) {
assert.notOk(_.isSafeInteger('1'), 'strings are not safe integers');
assert.notOk(_.isSafeInteger(null), 'null is not a safe integer');
assert.notOk(_.isSafeInteger(false), 'false is not a safe integer');
assert.notOk(_.isSafeInteger(NaN), 'NaN is not a safe integer');
assert.notOk(_.isSafeInteger(void 0), 'undefined is not a safe integer');
assert.notOk(_.isSafeInteger(10.01), 'floats are not safe integers');
assert.notOk(_.isSafeInteger(), 'nothing is not safe integers');
assert.ok(_.isSafeInteger(1), 'numbers are safe integers');
assert.ok(_.isSafeInteger(-10), 'integers are safe integers');
});

QUnit.test('isError', function(assert) {
assert.notOk(_.isError(1), 'numbers are not Errors');
assert.notOk(_.isError(null), 'null is not an Error');
Expand Down
4 changes: 4 additions & 0 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -1344,6 +1344,10 @@
return obj != null && hasOwnProperty.call(obj, key);
};

_.isSafeInteger = function(obj) {
return _.isNumber(obj) && _.isFinite(obj) && toString.call(parseInt(obj, 10)) === '[object Number]' && Math.floor(obj) === obj;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the third condition really necessary here? It seems kind of redundant with the first. Also, maybe the first is a bit too lenient. The standard seems to suggest that object-wrapped numbers are not allowed, so it should probably be typeof obj === 'number'.

};

// Utility Functions
// -----------------

Expand Down