diff --git a/object/ensure-integer.js b/object/ensure-integer.js new file mode 100644 index 00000000..9ec64b5b --- /dev/null +++ b/object/ensure-integer.js @@ -0,0 +1,9 @@ +"use strict"; + +var toShortString = require("../to-short-string-representation") + , isInteger = require("./is-integer"); + +module.exports = function (num) { + if (!isInteger(num)) throw new TypeError(toShortString(num) + " is not a integer"); + return Number(num); +}; diff --git a/object/index.js b/object/index.js index a69a5683..55de3e7c 100644 --- a/object/index.js +++ b/object/index.js @@ -12,6 +12,7 @@ module.exports = { create: require("./create"), ensureArray: require("./ensure-array"), ensureFiniteNumber: require("./ensure-finite-number"), + ensureInteger: require("./ensure-integer"), ensureNaturalNumber: require("./ensure-natural-number"), ensureNaturalNumberValue: require("./ensure-natural-number-value"), ensurePromise: require("./ensure-promise"), @@ -31,6 +32,7 @@ module.exports = { isCopyDeep: require("./is-copy-deep"), isEmpty: require("./is-empty"), isFiniteNumber: require("./is-finite-number"), + isInteger: require("./is-integer"), isNaturalNumber: require("./is-natural-number"), isNaturalNumberValue: require("./is-natural-number-value"), isNumberValue: require("./is-number-value"), diff --git a/object/is-integer.js b/object/is-integer.js new file mode 100644 index 00000000..1745b829 --- /dev/null +++ b/object/is-integer.js @@ -0,0 +1,10 @@ +"use strict"; + +var isInteger = require("../number/is-integer") + , isValue = require("./is-value"); + +module.exports = function (arg) { + if (!isValue(arg)) return false; + arg = Number(arg); + return isInteger(arg); +}; diff --git a/test/object/ensure-integer.js b/test/object/ensure-integer.js new file mode 100644 index 00000000..03db9c36 --- /dev/null +++ b/test/object/ensure-integer.js @@ -0,0 +1,42 @@ +"use strict"; + +module.exports = function (t, a) { + a.throws( + function () { + t(undefined); + }, + TypeError, + "Undefined" + ); + a.throws( + function () { + t(null); + }, + TypeError, + "Null" + ); + a(t(2), 2, "Number"); + a(t(-2), -2, "Negative"); + a.throws( + function () { + t(2.34); + }, + TypeError, + "Float" + ); + a(t("23"), 23, "Numeric string"); + a.throws( + function () { + t(NaN); + }, + TypeError, + "NaN" + ); + a.throws( + function () { + t(Infinity); + }, + TypeError, + "Infinity" + ); +}; diff --git a/test/object/is-integer.js b/test/object/is-integer.js new file mode 100644 index 00000000..a0bcd5cd --- /dev/null +++ b/test/object/is-integer.js @@ -0,0 +1,12 @@ +"use strict"; + +module.exports = function (t, a) { + a(t(undefined), false, "Undefined"); + a(t(null), false, "Null"); + a(t(2), true, "Number"); + a(t(-2), true, "Negative"); + a(t(2.34), false, "Float"); + a(t("23"), true, "Numeric string"); + a(t(NaN), false, "NaN"); + a(t(Infinity), false, "Infinity"); +};