Skip to content

Commit

Permalink
feat(date): isTimeValue and ensureTimeValue utils
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Nov 23, 2017
1 parent a9c62da commit 7659dc5
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 0 deletions.
10 changes: 10 additions & 0 deletions date/ensure-time-value.js
Original file line number Diff line number Diff line change
@@ -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");
};
2 changes: 2 additions & 0 deletions date/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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")
};
12 changes: 12 additions & 0 deletions date/is-time-value.js
Original file line number Diff line number Diff line change
@@ -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;
};
14 changes: 14 additions & 0 deletions test/date/ensure-time-value.js
Original file line number Diff line number Diff line change
@@ -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"
);
};
15 changes: 15 additions & 0 deletions test/date/is-time-value.js
Original file line number Diff line number Diff line change
@@ -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");
};

0 comments on commit 7659dc5

Please sign in to comment.