UNPKG

visiting-hours

Version:

An advanced, feature rich, optimised and tiny visiting-hours library.

263 lines (221 loc) 11.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Utils = void 0; var _Timezone = require("./Timezone"); var _VisitingHour = require("./VisitingHour"); function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var Utils = /*#__PURE__*/function () { function Utils() { _classCallCheck(this, Utils); } _createClass(Utils, null, [{ key: "isLeapYear", value: function isLeapYear(date) { return new Date(date.getFullYear(), 1, 29).getDate() === 29; } }, { key: "dayNumber", value: function dayNumber(name) { return Utils.dayNames.indexOf(name); } }, { key: "dayName", value: function dayName(index) { return Utils.dayNames[index]; } /** * Create an array of times between `startAt` and `endAt` with an interval of `interval` minutes. * Each entry in the array is a VisitingHour instance for easy manipulation. * * Example: minuteInterval('07:55', '09:00', 15); // ['08:00', '08:15', '08:30', '08:45', '09:00'] * * @param startAt * @param endAt * @param interval * @param {Date} [forDate] What date the range is for. Adds a timestamp to the VisitingHour. */ }, { key: "minuteInterval", value: function minuteInterval(startAt, endAt) { var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 15; var forZone = arguments.length > 3 ? arguments[3] : undefined; var forDate = arguments.length > 4 ? arguments[4] : undefined; var _startAt$split$map = startAt.split(':').map(Number), _startAt$split$map2 = _slicedToArray(_startAt$split$map, 2), sh = _startAt$split$map2[0], sm = _startAt$split$map2[1]; var _endAt$split$map = endAt.split(':').map(Number), _endAt$split$map2 = _slicedToArray(_endAt$split$map, 2), eh = _endAt$split$map2[0], em = _endAt$split$map2[1]; var lastStep = 60 - interval; var trailing = sm % interval; var startMinute = sm > lastStep ? 0 : sm - trailing + (trailing ? interval : 0); var lastMinute = em - em % interval; var startHour = sh + (sm > lastStep ? 1 : 0); var endHour = eh >= startHour ? eh : eh + 24; var values = []; for (var ip = startHour; ip <= endHour; ip++) { var i = ip % 24; for (var j = startHour === i ? startMinute : 0; j <= (i === endHour ? lastMinute : lastStep); j += interval) { var _forDate$getTime; values.push(new _VisitingHour.VisitingHour({ hours: i, minutes: j, zone: forZone, relativeToTimestamp: (_forDate$getTime = forDate === null || forDate === void 0 ? void 0 : forDate.getTime()) !== null && _forDate$getTime !== void 0 ? _forDate$getTime : undefined })); } } return values; } }, { key: "fromLuxon", value: function fromLuxon(date) { var month = date.month, zoneName = date.zoneName, offset = date.offset, day = date.day, weekday = date.weekday, hour = date.hour, minute = date.minute, isInLeapYear = date.isInLeapYear; return { month: month - 1, ts: date.valueOf(), offset: -offset, zoneName: zoneName, weekday: weekday, isInLeapYear: isInLeapYear, day: day, hour: hour, minute: minute }; } }, { key: "fromDate", value: function fromDate(inputDate, zone) { var date = typeof zone === 'string' ? _Timezone.Timezone.utcToZonedTime(inputDate, zone) : inputDate; return { zoneName: zone, get isInLeapYear() { return Utils.isLeapYear(date); }, offset: date.getTimezoneOffset(), ts: date.getTime(), month: date.getMonth(), day: date.getDate(), weekday: date.getDay(), hour: date.getHours(), minute: date.getMinutes() }; } }, { key: "dateName", value: function dateName() { var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); return Utils.dayName(date.getDay()); } }, { key: "nextDay", value: function nextDay(day) { return (day + 1) % 7; } }, { key: "toMilitary", value: function toMilitary(hours, minutes) { return "".concat(hours.toString().padStart(2, '0'), ":").concat(minutes.toString().padStart(2, '0')); } }, { key: "buildSpecialIndex", value: function buildSpecialIndex(special) { return special.reduce(function (acc, specialHour) { if (!specialHour.date) { throw new Error('Missing required date for special hours entry.'); } var _specialHour$date$spl = specialHour.date.split('/').map(Number), _specialHour$date$spl2 = _slicedToArray(_specialHour$date$spl, 2), d = _specialHour$date$spl2[0], month = _specialHour$date$spl2[1]; var m = month - 1; var key = "".concat(d, "/").concat(m); acc[key] = Utils.makeDayIndex(specialHour, acc, acc[key], function () { var tomorrow = new Date(Date.UTC(1972, m, d + 1)); var nextKey = "".concat(tomorrow.getDate(), "/").concat(tomorrow.getMonth()); if (m === 1 && d === 28) return Utils.leapYearKey; if (m === 1 && d === 29) return Utils.postLeapYearKey; return nextKey; }); return acc; }, {}); } }, { key: "buildIndex", value: function buildIndex(regular) { return Reflect.ownKeys(regular).reduce(function (index, key) { var dayNumber = Utils.dayNumber(key); index[dayNumber] = Utils.makeDayIndex(regular[key], index, index[dayNumber], function () { return Utils.nextDay(dayNumber); }); return index; }, {}); } }, { key: "timeValues", value: function timeValues(_ref) { var open = _ref.open, close = _ref.close; return [+open.replace(':', ''), +close.replace(':', '')]; } }, { key: "makeDayIndex", value: function makeDayIndex(day, index, fallback, nextKey) { var _day$hours$reduce, _day$hours, _fallback$hours; return _objectSpread(_objectSpread({}, fallback), {}, { open: day.isOpen, raw: day.hours, hours: (_day$hours$reduce = (_day$hours = day.hours) === null || _day$hours === void 0 ? void 0 : _day$hours.reduce(function (acc, h) { var _Utils$timeValues = Utils.timeValues(h), _Utils$timeValues2 = _slicedToArray(_Utils$timeValues, 2), o = _Utils$timeValues2[0], c = _Utils$timeValues2[1]; if (o < c) { acc.push([o, c]); } else { var _nd$hours; var nextDay = nextKey(); var nd = index[nextDay]; index[nextDay] = _objectSpread(_objectSpread({}, nd), {}, { hours: [[0, c]].concat(_toConsumableArray((_nd$hours = nd === null || nd === void 0 ? void 0 : nd.hours) !== null && _nd$hours !== void 0 ? _nd$hours : [])), pastMidnight: true }); acc.push([o, 2400]); } return acc; }, (_fallback$hours = fallback === null || fallback === void 0 ? void 0 : fallback.hours) !== null && _fallback$hours !== void 0 ? _fallback$hours : [])) !== null && _day$hours$reduce !== void 0 ? _day$hours$reduce : [] }); } }]); return Utils; }(); exports.Utils = Utils; _defineProperty(Utils, "leapYearKey", '__leapYear'); _defineProperty(Utils, "postLeapYearKey", '__postLeapYear'); _defineProperty(Utils, "dayNames", ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']);