Skip to content

Instantly share code, notes, and snippets.

@NhanHo
Created August 23, 2016 05:22
Show Gist options
  • Save NhanHo/3f7c74f76fd36ef6447996679d777597 to your computer and use it in GitHub Desktop.
Save NhanHo/3f7c74f76fd36ef6447996679d777597 to your computer and use it in GitHub Desktop.

Exhibit A on the goodness of Javascript:

Module is-positive-integer

First implementation:

var passAll = require('101/pass-all')
var isPositive = require('is-positive')
var isInteger = require('is-integer')

module.exports = passAll(isPositive, isInteger)

"Drastically simplified code":

module.exports = function (x) {
  return x >> 0 === x && x >> 0 > 0
}

Current version:

/* $lab:coverage:off$ */
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991
/* $lab:coverage:on$ */

module.exports = isPositiveInteger
module.exports.isSafePositiveInteger = isSafePositiveInteger

function isPositiveInteger (x) {
  // Is it a number?
  return Object.prototype.toString.call(x) === '[object Number]' &&
    // Is it an integer?
    x % 1 === 0 &&
    // Is it positive?
    x > 0
}

// strict positive integer check:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
function isSafePositiveInteger (x) {
  return isPositiveInteger(x) &&
    x <= MAX_SAFE_INTEGER
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment