From 7659dc59eff454ee700dd3afde853962378141c9 Mon Sep 17 00:00:00 2001 From: Mariusz Nowak Date: Thu, 23 Nov 2017 11:01:06 +0100 Subject: [PATCH] feat(date): isTimeValue and ensureTimeValue utils --- date/ensure-time-value.js | 10 ++++++++++ date/index.js | 2 ++ date/is-time-value.js | 12 ++++++++++++ test/date/ensure-time-value.js | 14 ++++++++++++++ test/date/is-time-value.js | 15 +++++++++++++++ 5 files changed, 53 insertions(+) create mode 100644 date/ensure-time-value.js create mode 100644 date/is-time-value.js create mode 100644 test/date/ensure-time-value.js create mode 100644 test/date/is-time-value.js diff --git a/date/ensure-time-value.js b/date/ensure-time-value.js new file mode 100644 index 00000000..09f5afcf --- /dev/null +++ b/date/ensure-time-value.js @@ -0,0 +1,10 @@ +"use strict"; + +var safeToString = require("../safe-to-string") + , toInteger = require("../number/to-integer") + , isTimeValue = require("./is-time-value"); + +module.exports = function (value) { + if (isTimeValue(value)) return toInteger(value); + throw new TypeError(safeToString(value) + " is not a valid time value"); +}; diff --git a/date/index.js b/date/index.js index 507e5e69..c1431497 100644 --- a/date/index.js +++ b/date/index.js @@ -2,6 +2,8 @@ module.exports = { "#": require("./#"), + "ensureTimeValue": require("./ensure-time-value"), "isDate": require("./is-date"), + "isTimeValue": require("./is-time-value"), "validDate": require("./valid-date") }; diff --git a/date/is-time-value.js b/date/is-time-value.js new file mode 100644 index 00000000..4240fec5 --- /dev/null +++ b/date/is-time-value.js @@ -0,0 +1,12 @@ +"use strict"; + +module.exports = function (value) { + try { + value = Number(value); + } catch (e) { + return false; + } + if (isNaN(value)) return false; + if (Math.abs(value) > 8.64e16) return false; + return true; +}; diff --git a/test/date/ensure-time-value.js b/test/date/ensure-time-value.js new file mode 100644 index 00000000..39ddc23c --- /dev/null +++ b/test/date/ensure-time-value.js @@ -0,0 +1,14 @@ +"use strict"; + +module.exports = function (t, a) { + a(t(12), 12, "Number in range"); + a(t(12.23), 12, "Rounds number in range"); + a(t(-12.63), -12, "Rounds negative number in range"); + a.throws( + function () { + t(NaN); + }, + TypeError, + "Throws on invalid" + ); +}; diff --git a/test/date/is-time-value.js b/test/date/is-time-value.js new file mode 100644 index 00000000..a21677c0 --- /dev/null +++ b/test/date/is-time-value.js @@ -0,0 +1,15 @@ +"use strict"; + +module.exports = function (t, a) { + a(t("arar"), false, "String"); + a(t(12), true, "Number in range"); + a(t(true), true, "Boolean"); + a(t(new Date()), true, "Date"); + a(t({}), false, "Plain object"); + a(t(NaN), false, "NaN"); + a(t(Infinity), false, "Infinity"); + a(t(8.64e17), false, "Beyond range"); + a(t(8.64e15), true, "Below range"); + a(t(-8.64e17), false, "Negative beyond range"); + a(t(-8.64e15), true, "Negative below range"); +};